gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:10:20 24 4
gpt4 key购买 nike

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

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

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

这是 fiddle : 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 中呈现,以便您可以操纵它的事件集合。

一旦该元素可访问,取消绑定(bind)插件的处理程序、绑定(bind)您的处理程序并重新绑定(bind)插件的处理程序就非常简单,因为您知道 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');

如果你不想解除绑定(bind),我相信你也可以使用DOM level 0事件模型并做:

element.onclick = yourHandler;

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

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

如果您的目标是现代浏览器,您可以使用 MutationObserver监听 DOM 变化的对象。

关于javascript - jQuery.on ('click' ) 在 jQuery.click 之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22106192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com