Answer the question
In order to leave comments, you need to log in
How to get the current index of an element in native JS?
Hello! In jQuery, finding out the current index of an element is not difficult, how to write a loop like this:
var buttons1 = $('button');
buttons1.each(function(i) {
$(this).click(function() {
alert(i + 1);
});
});
var buttons = document.querySelectorAll('button');
for(var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.onclick = function() {
alert(this.innerHTML + i);
}
}
Answer the question
In order to leave comments, you need to log in
var buttons = document.querySelectorAll('button');
for(var i = 0; i < buttons.length; i++) {
(function(i) {
var button = buttons[i];
button.onclick = function() {
alert(button.innerHTML + i);
}
})(i);
}
You need to wrap your function in a closure .
That's why .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question