JavaScript

作用域和事件委托

2017-04-25  本文已影响17人  LuckyS007

1.作用域

<body>
    <ul>
        <li>0</li>
        <li>1</li>
        <li>2</li>
    </ul>
    <script>
    //var 没有块级作用域  输出是3 3 3
        /*var node = document.querySelectorAll('ul li')
        for(var i = 0;i<node.length;i++){
            node[i].addEventListener('click',function(){
                alert('click'+i)
            })
        }*/

    //闭包 、输出1.2.3
        /*var node = document.querySelectorAll('ul li')
        for(var i = 0;i<node.length;i++){
            (function(i){
                node[i].addEventListener('click',function(){
                    alert('click'+i)
                })
            })(i)
        }*/

    //forEach
        var node = document.querySelectorAll('ul li')
            Array.from(node).forEach(function(nodeItem,index){
                nodeItem.addEventListener('click',function(){
                    alert('click'+index)
                })
            })
    </script>
</body>
2.事件委托
<body>
<ul>
    <li>0</li>
    <li>1</li>
    <li>2</li>
</ul>
<button>添加li元素</button>
<script>
    var ul = document.querySelectorAll('ul')[0]
    var addButton = document.querySelectorAll('button')[0]
    var addIndex = 3

    addButton.addEventListener('click',function(){
        var addli = document.createElement('li')
        addli.innerHTML = `这是添加的元素${addIndex}`
        ul.append(addli)
        addIndex++
    })

    ul.addEventListener('click',function(e){
      //e  是事件源
        var ev = ev || window.event; //ie兼容写法
        var target = ev.target || ev.srcElement;
        if(target.nodeName.toLocaleLowerCase() == 'li'){
            alert(target.innerHTML)
        }
    })
</script>
</body>
2.1递归调用 触发li的子节点时,准确定位到每个li
<body>
<ul>
    <li id="1">
        <span>span元素</span>
    </li>
    <li id="2">
        <div>
            <span>div包着一个span元素</span>
        </div>
    </li>
    <li id="3">
        <div>div元素</div>
    </li>

</ul>
<script>
    var ul = document.querySelectorAll('ul')[0]

    ul.addEventListener('click',function(e){
        var ev = ev || window.event;
        var target = ev.target || ev.srcElement;
        while(target.nodeName !== ul){
           if(target.nodeName.toLocaleLowerCase() == 'li'){
              console.log(target.id)
              alert(target.innerHTML)
              break
           }
           target = target.parentNode
        }
    })
</script>
</body>
上一篇下一篇

猜你喜欢

热点阅读