Project scene:
When you do cross click you want to get the index of the clicked element but the index is the length of the element’s length
cause the problem:
Loop problem
- The execution process of the FO loop is to first execute statement 1, that is, declare the value of i and set the value to 0, then judge whether it is less than 3, then execute the statement in parentheses, and then ++i;;
- Since the VAR statement is declared as a global variable, the value of I is 3 after the loop ends.
Example
for (var i = 0; i < 3; i++) {
console.log('I =' в цикле+ i);
}
console.log('I =' после окончания цикла+i)
Answer
1 Use the LET DECLARE functions
In a loop, each loop of the Let’s statement will form a separate space.
for (let i = 0; i < btns.length; i++) {
btns[i].onclick=function(){
console.log('Индексы элементов'+i);
}
}
2 Add a custom attribute to each element
user attributes is equal to the current value of I.
for (var i = 0; i < btns.length; i++) {
btns[i].dataset.index=i
btns[i].onclick=function(){
console.log('Индексы элементов'+this.dataset.index);
}
}
3 independent work function
If you add an event, add a self-contained function that will be executed each time.
for (var i = 0; i < btns.length; i++) {
(function (i) {
btns[i].onclick = function () {
console.log('Индексы элементов' + i);
}
}
)(i)
}