捕获 JavaScript onClick JQuery
我有一个 div,当用户单击链接时会弹出一个 div,该链接将使他们离开该网站的英文版本。他们可以选择是或否来继续。我必须捕获他们单击“是”后将前往的“URL”。对于作为 href 的链接来说这很容易,但有些链接是执行 JavaScript 的 onClicks。我必须捕获 JavaScript,阻止其执行,然后在他们单击“是”时执行它。这是我得到的捕获 onClick 代码,但是如何让它工作?
$_('a#foo').live('click', function(event) {
var onclick = $(this).attr("onclick");
$_('#yes a').attr('onclick', onclick);*/
return false;
event.preventDefault();
});
是按钮/div
$_('#yes').live('click', function() {
if(href) {
window.location=href;
};
if(onclick) {
eval(onclick);
}
});
I have a div that pops up when a user clicks on a link that will take them off of the english version of the site. They are given a yes or no choice to proceed. I have to capture the "URL" of where they will go to if they click yes. This is easy on the links that are a hrefs, but some of the links are onClicks that execute JavaScript. I have to capture the JavaScript, keep it from executing, and then execute it if they click yes. This is the capture onClick code I've got, but how do I get it to work?
$_('a#foo').live('click', function(event) {
var onclick = $(this).attr("onclick");
$_('#yes a').attr('onclick', onclick);*/
return false;
event.preventDefault();
});
the yes button/div
$_('#yes').live('click', function() {
if(href) {
window.location=href;
};
if(onclick) {
eval(onclick);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个工作演示
基本上,如果在 html 中定义了 onclick 属性,则可以通过以下方式访问它:
somelink.onclick
这只是一个函数,因此不需要eval
然而,诀窍是, onclick 属性中定义的代码将在 jQuery 之前执行
live()
事件处理程序,因此您必须通过删除原始的 onclick 函数但保留一个可以稍后执行的副本来避免这种情况。Here's a working demo
Basically, if an onclick attribute is defined in the html, it'll be accessible as
somelink.onclick
which is just a function, so there's no need foreval
The trick is however, that code defined in an onclick-attribute will execute before the jQuery
live()
event handler, so you have to avoid that by removing the original onclick function but keeping a copy you can execute later.