for(var i = 0;i<btnArr.length;i++){ btnArr[i].addEventListener('click',function(){ tabCardShow(i); }); }
Ordinary for loop, the value of incoming trigger event i must be equal to btnArr.length, the value of i stay in the loop is executed after completion, it does not meet the original intention.
The reason: i only acts on the scope of the for loop, with a value of i passed when all the elements are binding for the scope, value and i stay in the loop on the value of the last time.
for(var i = 0;i<btnArr.length;i++){ (function(i){ btnArr[i].addEventListener('click',function(){ tabCardShow(i); }) })(i); }
The reason: the closure of incoming i value, the equivalent of each cycle has created a scope, to pass the value of i, to avoid contamination, the cycling many times, there are that many scopes, there are that many values i .