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 last element in the loop. What am I doing wrong?
var navLinks = document.getElementsByClassName('navigation');
for (var i = 0; i < navLinks.length; i++) {
var navLink = navLinks[i];
navLink.onclick = function() { goTo.call(navLink); }
}
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.