码迷,mamicode.com
首页 > 其他好文 > 详细

事件委托

时间:2015-01-31 17:44:37      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

事件委托:利用事件冒泡的原理,把事件添加到父级身上,触发执行效果

好处:

1:提高性能。

2:新添加的元素,还会有之前的事件。

实例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>

window.onload = function(){

    var oUl = document.getElementById(ul1);
    var aLi = oUl.getElementsByTagName(li);
    var oInput = document.getElementById(input1);
    var iNow = 4;
    
    /*for(var i=0;i<aLi.length;i++){
        aLi[i].onmouseover = function(){
            this.style.background = ‘red‘;
        };
        
        aLi[i].onmouseout = function(){
            this.style.background = ‘‘;
        };
    }*/
    
    
    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(){
    
        iNow++;
        var oLi = document.createElement(li);
        oLi.innerHTML = 1111 * iNow;
        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>

 

事件委托

标签:

原文地址:http://www.cnblogs.com/liujin0505/p/4264265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!