Why does my jQuery click handler appear to run mul

2019-02-16 10:05发布

I apply:

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

On this:

<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>

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

7条回答
神经病院院长
2楼-- · 2019-02-16 10:10

Try giving different names to your submit input elements.

查看更多
在下西门庆
3楼-- · 2019-02-16 10:12

To make sure the function only execute once on one click event you may use $(".newContentLink").one();

$(".newContentLink").one(function() {
    $("#test").append("1");
});
查看更多
Viruses.
4楼-- · 2019-02-16 10:20

As chaos says, you're probably calling click() each time you add one, and they're accumulating.

If you're adding these items to the document dynamically, and need to make sure this function is added to every one you add, how about using live?

$('#contents').on('click', '.newContentLink', function() {
    $("#test").append("1");
});

This will make sure the rule is dynamically applied once to any qualifying class in the document.

查看更多
再贱就再见
5楼-- · 2019-02-16 10:23

or you can unbind the click event each time you add a new element

$('.newContentLink').unbind('click');

$(".newContentLink").click(function() {
    $("#test").append("1");
});
查看更多
放我归山
6楼-- · 2019-02-16 10:24

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.

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.

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

查看更多
迷人小祖宗
7楼-- · 2019-02-16 10:26

I had a similar problem.... Figured out that I was applying the change function in a loop...i.e. my earlier code was....

$("table#UserIRTable > tbody > tr").each(function()
{
   ..............
   ..............

  $("input[id='thisMonthSupply']").change(function(e){  
      ......
    });
  ..........
  ..........
}

took the change function out and bingo... it worked.....

查看更多
登录 后发表回答