有没有一种不那么黑客的方法可以防止我的 on('click') 触发两次

Is there a less hack-y way to prevent my on('click') from firing twice?

本文关键字:on 我的 click 两次 一种 黑客 有没有 方法      更新时间:2023-09-26

我有一个元素.trigger出现在我的页面顶部和底部。它是.center的子元素,也出现了两次。我的代码很简单:

$(document).unbind('click').on('click', '.trigger', function() {
    alert('success');
});

这对我来说很混乱,看起来像是一个黑客。 但是,如果我使用:

$(document).on('click', '.trigger', function() {
    alert('success');
});

它在点击时触发两次,我不知道为什么?谁能解释为什么会发生这种情况,以及如何防止它发生?如果我这样做:

$('.center').on('click', '.trigger', function() {
    alert('success');
});

然后它只会在第二个.trigger实例上触发(尽管它只会触发一次,正如我所期望的那样)。

谁能解释这三个案例的奇怪行为,并提供解决方案?

.HTML:

// some html
<div class="center">
    <div class="trigger">blah</div>
</div>
// lots of more html
<div class="center">
    <div class="trigger">blah</div>
</div>
// some html

编辑

.trigger的第一个块本质上是AJAX使用Foundation中名为data-interchange http://foundation.zurb.com/docs/components/interchange.html 的工具

本周早些时候,我搜索了一种方法来正则表达式整个DOM,并将字符串__LANG__的所有匹配项替换为当前选定的语言(例如:eng)(用于链接目的)。

代码是:

var replaced = $("body").html().replace(/_LANG_/g,lang);
$("body").html(replaced);

它取代了身体,但似乎也复制了我所有的script。如果您在 SE 上搜索使用 javascript str_replace字符串的所有实例的方法,上面的代码片段在结果中出现了很多,但我不建议使用它,因为替换整个DOM似乎是一个坏主意。

删除该代码后,我的代码停止触发两次。