Click on a Ul inside five li, the serial number of each pop them

method one:

var oLi = document.querySelector("li");
for(var i=0; i<oLis.length; i++){
    oLis[i].onclick = (function(j){
        return function(){
            alert(j);
        }
    })(i);
}

Method Two:

var oLi = document.querySelector("li");
for(var i=0; i<oLi.length; i++){
    (function(j){
        oLi[j].onclick = function(){
            alert(j);
        };
    })(i);
}

 Method three:

var oLi = document.getElementsByTagName('li');
    function func(obj,i){
        obj.onclick = function(){
            alert (i);
        }
    }
    for(var i = 0; i<oLi.length; i++){
        func(oLi[i], i);
    }

 

Method four:

var oLi = document.getElementsByTagName('li');
for(var i=0; i<oLi.length; i++){
    oLi[i].setAttribute("onclick", "alert("+i+");");
}

 

Method five:

for(var i=0; i<oLi.length; i++){
    oLi[i].index = i;
    oLi[i].onclick = function(){
        alert(this.index);
    }
}

 Method six:

<body>
    <input type="button" value="按钮1">
    <input type="button" value="按钮2">
    <input type="button" value="按钮3">
    <script type="text/javascript">
        var btns = document.getElementsByTagName("input");
        for (let i = 0; i < 3; i++) {
            btns [I] .onclick =  function () { 
                the console.log ( " I was the first "  + (I) +  " buttons " ); 
            }; 
        } 
    </ Script > 
</ body >

 

Guess you like

Origin www.cnblogs.com/haohao-a/p/10960848.html