Home  >  Article  >  Web Front-end  >  JS loop binds events to li. Click li to pop up its index value and content.

JS loop binds events to li. Click li to pop up its index value and content.

高洛峰
高洛峰Original
2016-10-12 12:33:311421browse

Recently, we always encounter such an interview question during interviews:

There are many answers online that I agree with, but I still want to repeat it. As the saying goes: A good memory is not as good as a bad writing. Although it is common, simple, and repeated, in short , even if you simply write more, your memory will be very profound. Even if you forget, you can still take it out and look through it.

The code is as follows: (simpler)

html code

     

  • banana
  •  

  • apple
  • pineapple
  •  

  • kiwi
  •  

  • Mango

Method 1:

var itemli = document.getElementsByTagName("li");

for(var i = 0; i

 itemli[i].index = i; //Define one for each li Attribute index value, assign

  itemli[i].onclick = function(){

   alert("The subscript index value is: "+this.index+"n"+"The text content is: "+this.innerHTML); // n Line break Index value starts from 0

  }

}

Method 2: (commonly used)

var itemli = document.getElementsByTagName("li");

for(var i = 0; i

  (function(n){

   itemli[i].onclick = function(){

   alert("The subscript index value is: "+n+"n"+"The text content is:" +itemli[n].innerHTML); // n line feed index value starts from 0

  }

 })(i)

 }

or:

for(var i = 0; i itemli[i ].onclick = function(n){
   return function(){
       alert("The subscript index value is: "+n+"n"+"The text content is: "+itemli[n].innerHTML); // n Line break Index value starts from 0
        }
      }(i)
  }

Method 3: jQuery (simpler)

$("ul li").click(function(){
      var item = $(this). index(); //Getting the index subscript also starts from 0
  var textword = $(this).text(); //Text content
                                                                                                                             . The text content is: "+textword); // nline break
})


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn