Set Current Element In Onclick Event Handler Loop
I'm looping over multiple elements, which I'd like to assign an onclick event handler too. The problem is that the element sent to the goTo function (event handler), is always the
Solution 1:
You should add a closure, like this:
var navLinks = document.getElementsByClassName('navigation');
for (var i = 0; i < navLinks.length; i++) {
var navLink = navLinks[i];
(function(navLink){ //This line does the magic
navLink.onclick = function() { goTo.call(navLink); }
})(navLink); //This calls the created function
}
This way, the inner navLink
will be unique per loop cycle, so it won't get overwritten (that's why it remained with the latest value in your previous code)
Cheers
Solution 2:
What am I doing wrong?
See JavaScript closure inside loops – simple practical example for an explanation.
Inside the event handler you can access the element itself via this
(this works also if you used addEventListener
to bind the handler instead):
navLink.onclick = function() { goTo.call(this); }
And assuming goTo
is a function, you can shorten the code to
navLink.onclick = goTo;
in your case.
Post a Comment for "Set Current Element In Onclick Event Handler Loop"