首页 > 代码库 > 点击ul中的li弹出其索引值

点击ul中的li弹出其索引值

html结构

<ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>

 

JQuery实现:

 $("ul").on("click","li",function(){
        var index=$("li").index($(this));
       alert(index)
    })

js实现:

 var myul = document.querySelector(‘ul‘);
    var list = document.querySelectorAll(‘ul li‘);

    myul.addEventListener(‘click‘, function(ev){
        var ev = ev || window.event;
        var target = ev.target || ev.srcElemnt;

        for(var i = 0, len = list.length; i < len; i++){
            if(list[i] == target){
                alert(i);
            }
        }
    });

 

点击ul中的li弹出其索引值