For example, I have 10 a tags generated from an AJAX response:
<a href="#" id="b1">b1</a> <a href="#" id="b2">b2</a> <a href="#" id="b3">b3</a> <a href="#" id="b4">b4</a> <a href="#" id="b5">b5</a> <a href="#" id="b6">b6</a> <a href="#" id="b7">b7</a> <a href="#" id="b8">b8</a> <a href="#" id="b9">b9</a> <a href="#" id="b10">b10</a>
I need to assign onclick event to each of them via loop:
for(i=1; i<11; i++) { document.getElementById("b"+i).onclick=function() { alert(i); } }
This doesn't work, it only assigns onclick to the last a tag and alerts "11". How can I get this to work? I'd prefer not to use jQuery.
The addEventListener() method You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling.
One event can have more than one event handler method in the same class or in different classes. At the run time only one handler method will be triggered at a time. After triggering the one that has to be deactivated and then another handler method will have to be registered to be triggered.
Event handlers are the JavaScript code that invokes a specific piece of code when a particular action happens on an HTML element. The event handler can either invoke the direct JavaScript code or a function.
All of your handlers are sharing the same i
variable.
You need to put each handler into a separate function that takes i
as a parameter so that each one gets its own variable:
function handleElement(i) { document.getElementById("b"+i).onclick=function() { alert(i); }; } for(i=1; i<11; i++) handleElement(i);
A closure is what you're looking for:
for(i=1; i<11; i++) { (function(i) { document.getElementById("b"+i).onclick=function() { alert(i); }; })(i); }
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