一个ul中含有1000甚至更多li的时候,点击当前li打印是第几

2019-04-13  本文已影响0人  郭先生_515

话不多说

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <ul class="oul">
        
    </ul>
</body>
<script>
    var oul = document.getElementsByClassName('oul')[0]
    var liArr = document.getElementsByTagName('li')
    var str = ''
    for (var i = 1; i <= 10; i++) {
        str += '<li>'+i+'</li>'
    }
    oul.innerHTML = str
    for (var i = 0; i < liArr.length; i++) {
        liArr[i].index = i+1
        liArr[i].onclick = function() {
            console.log('您点击了第'+this.index+'个li');
        }
    }
</script>
</html>

这样写有个问题,就是当li有100000个甚至更多的时候,就会有较长的等待时间,怎么解决呢? 那就是事件委托了!怎么做呢

var oul = document.getElementsByClassName('oul')[0]
var liArr = document.getElementsByTagName('li')
var str = ''
for (var i = 1; i <= 10; i++) {
    str += '<li>'+i+'</li>'
}
oul.innerHTML = str
oul.onclick=function(ev) {
    var ev = ev || window.event
    var target = ev.target || ev.srcElement
    if (target.nodeName.toLowerCase() == 'li'){
        var index;
        for (var i = 0; i < liArr.length; i++) {
            if (target == liArr[i]){
                index = i+1
                console.log('您点击了第'+index+'个li');
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读