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
})