The code is as follows:
HTML code
<ul>
<li> Real Estate </li>
<li> Home </li>
<li> Secondhand </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