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

Pie*_*ger 6 javascript jquery analytics

我有一个外部脚本,我无法修改.这个脚本加载一个按钮,并在其上添加一个jQuery .click ...它以"return false"结束.

我需要在这次点击时触发我自己的代码.当我加载页面时,不存在,所以我需要使用.on('click')来绑定"live".但看起来.on('click')在".click之后"加载,并且当他使用"return false"时,我的.on('click')没有被加载.

所以问题是......如何触发我点击这个动态加载的#btn已经有一个.click函数返回false?

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

这里有一个代码示例:

<div id="container"></div>
Run Code Online (Sandbox Code Playgroud)
// 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 ;
}) ;
Run Code Online (Sandbox Code Playgroud)

尽可能地,目标是在由远程脚本加载的链接按钮上触发Google Analytics事件.

pla*_*alx 5

似乎您面临着多个问题,但更重要的是知道元素何时在 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');
Run Code Online (Sandbox Code Playgroud)

如果你不想解绑,相信你也可以使用DOM level 0事件模型,这样做:

element.onclick = yourHandler;
Run Code Online (Sandbox Code Playgroud)

知道,如果插件异步呈现该元素并且不提供知道该过程何时完成的方法,则知道该元素何时可用是一个更大的问题。

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

如果您的目标是现代浏览器,则可以使用该MutationObserver对象来侦听 DOM 更改。