捕获 JavaScript onClick JQuery

发布于 2024-12-02 07:07:43 字数 597 浏览 1 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戴着白色围巾的女孩 2024-12-09 07:07:43

这是一个工作演示

基本上,如果在 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 for eval

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文