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

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

问题描述

我申请:

$(".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>

怎么会当我单击前 2 个按钮时,它会添加 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") (这始终意味着 every .newContentLink).

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

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

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