Js loops bind events to li. Click li to bring up its index value and content.

Source: Internet
Author: User
Js loops bind events to li implementation click li to bring up its index value and content recently, we will always encounter this interview question:

There are many different answers on the Internet, but I still want to repeat them. As the saying goes: Good memory is not as bad as a pen. Although it is common, simple, and repeated, in short, the simple multi-write memory is still profound. Even if you forget it, you can flip it out.

The Code is as follows: (simpler)

Html code

      

  • Bananas
  •   

  • Apple
  • Pineapple
  •   

  • Kiwifruit
  •   

  • Mango

Method 1:

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

For (var I = 0; I

Itemli [I]. index = I; // define an attribute index value for each li

Itemli [I]. onclick = function (){

Alert ("subscript index value:" + this. index + "\ n" + "text content:" + this. innerHTML); // \ n line feed 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 ("subscript index value:" + n + "\ n" + "text content:" + 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 ("subscript index value:" + n + "\ n" + "text content:" + itemli [n]. innerHTML); // \ n line feed index value starts from 0
}
} (I)
}

Method 3: jQuery (simpler)

$ ("Ul li"). click (function (){
Var item = $ (this). index (); // obtain the index subscript from 0.
Var textword = $ (this). text (); // text content
Alert ("subscript index value:" + item + "\ n" + "text content:" + textword); // \ n line feed
})

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.