English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Share an Interview Question about Closure, bind, and this

The problem to be solved is to add a click event to each li under this ul, and pop up the corresponding index

<ul id="text">
 <li>This is the first li</li>
 <li>This is the second li</li>
 <li>This is the third li</li>
</ul>

Answer one:bind, which points the current anonymous function to this and takes i as a 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 two: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();

Answer three:The most naive method, match

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();

Summary

That's all for this article. I hope the content of this article can bring you some help in learning or working. If you have any questions, you can leave messages for communication.

Statement: The content of this article is from the network, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace '#' with '@' when sending an email to report infringement. Provide relevant evidence, and once verified, this site will immediately delete the content suspected of infringement.

You May Also Like