Native js implements a Lianliankan mini game (3) ------------- Click on the list to get the index

  Requirement: When clicking on a list, we need to know which item it is in the list, that is, the index. The code is implemented as follows:

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

  <ul id="myUl">
    <li> 1st individual li </ li>
    <li> 1st individual li </ li>
    <li> 1st individual li </ li>
    <li> 1st individual li </ li>
  </ul>


  <script type="text/javascript">
    var ul=document.getElementById('myUl' );
     var li=document.getElementsByTagName('li' );
     // console.log(li.length) 

    ul.onclick = function (e){
       for ( var i=0; i<li.length;i++ ){
           // The current clicked item is found in the list 
          if (e.target== li[i]){
            console.log(li[i].innerHTML);
          }
      }
    }
  
  </script>


</body>
</html>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324894199&siteId=291194637