jQuery.on('click') 在 jQuery.click 之前?

2024-03-15

我有一个外部脚本,我无法修改它。该脚本加载一个<a>按钮,并添加一个 jQuery。单击它...并以“return false”结束。

我需要在这次点击时触发我自己的代码。当我加载页面时<a>不存在,所以我需要使用.on('click')绑定“活”。但看起来像.on('click')在 .click“之后”加载,当他使用“return false”时,我的.on('click')未加载。

所以问题是...我怎样才能触发我对这个动态加载的 a#btn 的点击,它已经有一个返回 false 的 .click 函数?

这是小提琴:http://jsfiddle.net/PLpqU/ http://jsfiddle.net/PLpqU/

这里是一个代码示例:

<div id="container"></div>
// I want this action to be executed on click, and the other too
// I can't use .click because on the "real" code, the a#btn is loaded after the page by another script
jQuery(document).on('click','a#btn',function(){
        ga('send', 'event', { eventCategory: 'xxxx', eventAction: 'yyyy' });
}) ;

// http://www.xxxxxx.com/distant-script.js
// This one is binded in a script that I cannot edit :
// Just before it load a#btn on the page, and then bind .click on it
// as he return false, the other on('click') are not executed
jQuery('#container').append('<a id="btn" />') ;
jQuery('a#btn').click(function(){
    // Some code stuff I need to be executed, but I can't manage
    return false ;
}) ;

如您所知,目标是在远程脚本加载的链接按钮上触发 Google Analytics 事件。


您似乎面临多个问题,但更重要的一个是了解元素何时在 DOM 中呈现,以便您可以操作它的事件集合。

一旦该元素可访问,就可以非常简单地取消绑定插件的处理程序,绑定您的处理程序并重新绑定插件的处理程序,因为知道 jQuery 的事件集合可以像这样访问: $._data(domEl, 'events');

这是一个例子:

var $div = $('<div>').click(function () { console.log('plugin'); return false; }),
    clickListener = jQuery._data($div[0], 'events').click[0];

//unbind all
$div.off('click');

//bind yours
$div.click(function () { console.log('yours'); });

//rebind the plugin's one
//note that I do not register the listener by honoring the same configs, 
//but you could since you can see them in the clickListener object
$div.click(clickListener.handler);

//test out everyting
$div.triggerHandler('click');

如果你不想解除绑定,我相信你也可以使用DOM level 0事件模型并执行以下操作:

element.onclick = yourHandler;

要知道,如果插件异步渲染此元素并且不提供了解该过程何时完成的方法,那么了解该元素何时可用就更成问题了。

如果你想支持旧的浏览器,你别无选择,只能覆盖插件的代码(假设相关方法是公共的)或轮询 DOMsetInterval直到您要查找的元素成为 DOM 的一部分,然后您就可以执行我们上面讨论的操作。

如果您的目标是现代浏览器,则可以使用MutationObserver https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver监听 DOM 变化的对象。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jQuery.on('click') 在 jQuery.click 之前? 的相关文章

随机推荐