Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my jQuery click handler appear to run multiple times for some of its targets?

Tags:

jquery

onclick

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?

like image 756
Eliyahu Avatar asked Jul 24 '09 14:07

Eliyahu


People also ask

Why is this jQuery Ajax click event firing multiple times?

This happens because somewhere in your code, you're rebinding the event handler without first unbinding it.

How to bind the click event in jQuery?

jQuery bind() MethodUse the on() method instead. The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

Why jQuery click function is not working?

So Why Does It Happen? JQuery OnClick Method is bound to an element or selector on page ready/load. Therefore if that element you want to click isn't there at the time of page ready, the binding can't happen.

What is the difference between .click and .on (' click in jQuery?

So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.


1 Answers

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

like image 117
chaos Avatar answered Nov 16 '22 00:11

chaos