为什么我的jQuery Click处理程序似乎针对其某些目标多次运行? [英] Why does my jQuery click handler appear to run multiple times for some of its targets?

查看:84
本文介绍了为什么我的jQuery Click处理程序似乎针对其某些目标多次运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我申请:

$(".newContentLink").click(function() {
    $("#test").append("1");
});

关于此:

<span id="contents">
<input class="newContentLink" type="submit" style="width: 100%;" value="CREATE A NEW CONTENT"/>
<span id="content1" class="content study">
</span>
<input class="newContentLink" type="submit" style="width: 100%;" value="CREATE A NEW CONTENT"/>
<span id="content3" class="content study">
</span>
<input class="newContentLink" type="submit" style="width: 100%;" value="CREATE A NEW CONTENT"/>
<span id="content4" class="content category">
</span>
<input class="newContentLink" type="submit" style="width: 100%;" value="CREATE A NEW CONTENT"/>
</span>

怎么来 当我单击前两个按钮时,它会添加111, 下一个按钮添加11 最后一个加1?

How come when I click on the first 2 buttons it adds 111, the next button adds 11, and the last one adds 1?

推荐答案

无法复制.我怀疑您是在歪曲—过于简化,主要是—你的情况.确切地说,我相信您是在动态添加这些输入,并在每次—时调用$(".newContentLink").click(...).当然,该操作会继续将点击处理程序的其他副本应用于页面中的每个.newContentLink.

Unable to replicate. I suspect that you're misrepresenting — oversimplifying, mostly — your situation. To be precise, I believe you're dynamically adding those inputs, and calling $(".newContentLink").click(...) each time — which, naturally, keeps applying additional copies of the click handler to each .newContentLink in the page.

因此,您创建的最新输入具有单击处理程序的一个副本,并附加一个1.第二个最近的副本具有两个副本,并附加11.第三个有三个并附加111,等等.

So the most recent input you've created has one copy of the click handler and appends one 1. The second most recent has two copies and appends 11. The third has three and appends 111, etc.

为避免这种情况,请将点击处理程序应用于新创建的DOM元素,而不要应用于$(".newContentLink")(这始终表示每个 .newContentLink).

To prevent this, apply the click handler to your newly created DOM element, not $(".newContentLink") (which always means every .newContentLink).

这篇关于为什么我的jQuery Click处理程序似乎针对其某些目标多次运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆