Home >Web Front-end >JS Tutorial >JS loop binds events to li. Click li to pop up its index value and content.
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
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 Method 3: jQuery (simpler) $("ul li").click(function(){
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)
}
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
})