This article mainly introduces you to an interview question about closure bind and this. The article gives detailed sample code. Friends in need can refer to it. Let’s take a look together.
The problem to be solved is to add a click event for each li for the following ul, and pop up the corresponding index
<ul id="text"> <li>这是第一个li</li> <li>这是第二个li</li> <li>这是第三个li</li> </ul>
# #Answer 1: bind, point the current anonymous function to this, and pass i as the parameter
var init = function(){ var obj = document.getElementById('text'); for(var i=0;i<obj.children.length;i++){ obj.children[i].addEventListener('click',function(i){ alert(i) }.bind(this,i)) } } init();
Answer 2: Closure
var init = function(){ var lis=document.querySelectorAll("#text li"); for(var i=0;i<lis.length;i++){ lis[i].onclick=(function(i){ return function(){ alert(i); }; })(i) } } init();
Solution 3:The stupidest method, matching
var init = function(){ var obj = document.getElementById('text'); for(var i=0;i<obj.children.length;i++){ obj.children[i].addEventListener('click',function(item){ var self = item.target; for(var j=0;j<obj.children.length;j++){ if(self == obj.children[j]){ alert(j); } } }) } } init();