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?
This happens because somewhere in your code, you're rebinding the event handler without first unbinding it.
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.
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.
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With