js事件委托

事件委托其实就是利用冒泡,吧事件加到父级身上,从而出发执行。

事件委托有两个好处:1.提高性能。 2.后面动态添加的元素,也能有效果。具体可以看下面的代码。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>事件委托</title>
<script type="text/javascript">
window.onload = function(){
    var oUl = document.getElementById('ul1');
    var aLi = oUl.getElementsByTagName('li');
    var oInput = document.getElementById('input1');

    /*for(var i=0;i<aLi.length;i++){
        aLi[i].onmouseover = function(){
            this.style.background = 'red';
        }

        aLi[i].onmouseout = function(){
            this.style.background = '';
        }
    }*/
    /*event对象:有一个属性: 事件源,不管在任何事件中,就算是冒泡到父级的,事件源始终都是你操作的那个元素*/
    //兼容:ie:window.event.srcElement  标准下:event.target
    //nodeName:找到当前元素的标签名
    oUl.onmouseover = function(ev){
        var ev = ev || window.event;
        var target = ev.target || ev.srcElement;
        if( target.nodeName.toLowerCase()=='li' ){
            target.style.background = 'red';
        }
        
    }

    oUl.onmouseout = function(ev){
        var ev = ev || window.event;
        var target = ev.target || ev.srcElement;
        if( target.nodeName.toLowerCase()=='li' ){
            target.style.background = '';
        }
        
    }

    oInput.onclick = function(){
        var oLi = document.createElement('li');
        oLi.innerHTML = 'zwl';
        oUl.appendChild(oLi);
    }
    
}
</script>
</head>
<body>
    <input type="button" value="添加" id="input1" />
    <ul id="ul1">
        <li>111</li>
        <li>222</li>
        <li>333</li>
        <li>444</li>
    </ul>
</body>
</html>
原文地址:https://www.cnblogs.com/toodeep/p/4475569.html