In the near future, we always encounter such an interview question:
Now online answer a lot of agree, but I still want to repeat the story again, as the saying goes: good memory is not as bad as the written, although common, simple, recurring, in short, in a simple more write memory or very deep, even if forget, can also take out to turn over.
The code is as follows: (simpler)
HTML code
<ul>
<li> Banana </li>
<li> Apple </li>
<li> Pineapple </li>
<li> Kiwi </li>
<li> Mango </li>
</ul>
Method One:
var Itemli = document.getelementsbytagname ("Li");
for (var i = 0; i<itemli.length; i++) {
Itemli[i].index = i; Define an attribute index value for each LI, assigning
Itemli[i].onclick = function () {
Alert ("Subscript index value:" +this.index+ "\ n" + "text content is:" +this.innerhtml); \ nthe newline index value starts from 0
}
}
Method two: (Common)
var Itemli = document.getelementsbytagname ("Li");
for (var i = 0; i<itemli.length; i++) {
(function (n) {
Itemli[i].onclick = function () {
Alert ("Subscript index value:" +n+ "\ n" + "text content is:" +itemli[n].innerhtml); \ nthe newline index value starts from 0
}
}) (i)
}
OR OR:
for (var i = 0; i<itemli.length; i++) {
Itemli[i].onclick = function (n) {
return function () {
Alert ("Subscript index value:" +n+ "\ n" + "text content is:" +itemli[n].innerhtml); \ nthe newline index value starts from 0
}
} (i)
}
Method Three: JQuery (more simple)
$ ("ul Li"). Click (function () {
var item = $ (this). index (); Get index subscript also starting from 0
var Textword = $ (this). text (); Text content
Alert ("Subscript index Value:" + Item + "\ n" + "text content is:" +textword); \ nthe line break
})
Hope to help you, tidy up a bit.
JS Loop to Li bound event implementation Click Li to eject its index value and content