When you add a click event using a for loop, i get value method

For example, there is a ul, li on several pages, now add the click event to li.

    var li = document.getElementsByTagName("li");
    for(var i = 0; i < li.length; i  ) {
	li[i].addEventListener("click",function () {
	console.log(i);
	})
  }            

However, we find that after writing this, click on any li, the value of all print 5, since the closure of the CCP with the value of i, and i value due to execution of the for loop are become 5

In order to properly display the value of i, we can use the following method:

 

 for (var i = 0; i < lis.length; i  ) {
    (function(arg){
        li[arg].onclick = function(){
            console.log(arg);
        };
    })(i)   
 }

  

Like this

			var li = document.getElementsByTagName("li");
			for(var i = 0; i < li.length; i  ) {
				getConsole(i);
			}
			
			
			function getConsole(i){
				li[i].addEventListener("click", function() {
					console.log(i);
				});
				
			}

  

Original articles published 0 · won praise 2 · Views 8078

Guess you like

Origin blog.csdn.net/u011927449/article/details/103963332