Using JS output ul under Li's index value

Source: Internet
Author: User
Tags event listener

<! DOCTYPE html>

The above code will not correspond to the results we expect, and each click Output is the index of the last element.
Function (e) {} for anonymous functions, each of which creates a new scope when executed. These anonymous functions are not executed immediately, are simply defined, are executed only when clicked, and are passed into the AddEventListener function as arguments. So the value of I at execution time has changed to the last index value.

To solve this problem, we can use the following methods:

Scenario 1----The use of closures;

<Script>    varnodeList=document.getElementsByTagName ('Li');  for (varI= 0; I<nodelist.length; I++) {        (function(j) {Nodelist[j].addeventlistener ("Click", function(e) {console.log (j); }, false);    }) (i); }</Script>

Scenario 2-----Use a block-level scope of let in ES6;

<script>    var nodeList = document.getelementsbytagname (' li ');    for (Let i = 0; i < nodelist.length; i++) {       nodelist[i].addeventlistener ("click", Function (e) {            console.log (i)        }, False);    } </script>

Programme 3----The use of the event delegation mechanism;

If Li is less, it is possible to use the above approach, but if the number of Li is too high, adding an event listener for each Li will have a significant impact on page performance, which we can implement with a delegate. The role of Array.prototype.slice.call (NodeList) is to convert an element with the length property into an array, which takes advantage of the IndexOf method to get the index value of Li.

<script>    var nodeList = document.getelementsbytagname (' li ');    Arrnodes = Array.prototype.slice.call (nodeList);    Nodeuls = document.getElementsByTagName (' ul ');    Nodeuls[0].addeventlistener ("click", Function (event) {        var event = Event | | window.event;        var target = Event.target | | event.srcelement;        Console.log (Arrnodes.indexof (target))    },false);</script>

Scenario 4-----The use of virtual properties;

<Script>    varnodeList=document.getElementsByTagName ('Li');  for(varI=0; I<nodelist.length; I++) {Nodelist[i].index=i; Nodelist[i].addeventlistener ("Click",function(e) {Console.log ( This. Index)},false)    }</Script>

Scenario 5----The use of custom attributes;

Adding custom attributes to the Li tag in the UL>LI structure

<ul>    <li data-index= "0" >click</li>    <li data-index= "1" >click</li>    < Li data-index= "2" >click</li>    <li data-index= "3" >click</li>    <li data-index= "4" >click</li></ul>

Then the JS code is as follows

<script>    var nodeList = document.getelementsbytagname ("li");    for (var i=0; i<nodelist.length; i++) {        nodelist[i].addeventlistener ("click", Function (e) {            Console.log ( E.TARGET.DATASET.INDEX)///Custom attributes can be obtained using a dataset in Data-index format,  console.log (This.getattribute (" Data-index ")        },false)    }</script> 

  

Using JS output ul under Li's index value

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.