Two methods to pop up the list index by clicking the LIST _ javascript skills

Source: Internet
Author: User
The second method to use event bubbling to delegate to the parent node of the list is to use closures. If you are interested, refer to this article, which may be helpful for you to learn about js. Method 1: Use event bubbling to delegate to the parent node of the list for processing:

The Code is as follows:


Var ulObj = document. getElementById ("myUl ");
UlObj. onclick = function (event ){
Var tg = event.tar get;
Var liArray = ulObj. getElementsByTagName ("li ");
For (var I = 0; I <liArray. length; I ++ ){
If (liArray [I] === tg ){
Alert (I + 1 );
}
}
}


Method 2: Use closures:

The Code is as follows:


Var liArray = document. getElementById ("myUl"). getElementsByTagName ("li ");
For (var I = 0; I <liArray. length; I ++ ){
(Function (){
Var n = I;
LiArray [I]. onclick = function (){
Alert (n + 1 );
}
}) (I)
}


HTML code:

The Code is as follows:



  • Haha

  • Heihei

  • Hehe

  • Gaga

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.