事件模型(事件冒泡/事件委託)的整理

事件冒泡/捕獲

事件冒泡 事件捕獲
IE和標準瀏覽器 標準瀏覽器
傳播順序:先捕獲,後冒泡
早期IE只支持事件冒泡,不支持事件捕獲

image

綁定事件

.addEventListener('click',function(){},false) .attachEvent('onclick',function(){})
標準瀏覽器 IE
三個參數:
1.事件類型,沒有on
2.事件處理函數
3.布爾型的數值,默認false(事件冒泡),true(事件捕獲)
有兩個參數:
1.事件類型,有on
2.事件處理函數
阻止事件冒泡/捕獲 : e.stopPropagation(); 阻止事件冒泡 : window.event,cancelBubble=true
問題:
1.順序相反
2.this指向window

事件冒泡優勢

1.有不少子元素,而且綁定同一種事件,能夠委託給父元素代理(事件代理/事件委託)瀏覽器

<body>
<ul id="ul1">
    <li>001</li>
    <li>002</li>
    <li>003</li>
    <li>004</li>
    <li>005</li>
</ul>

<script>
    var oUl = document.getElementById('ul1');
    oUl.onclick = function(e){
        //獲取事件源
        var target=e?target = e.target:window.event.srcElement;
        console.log(target.innerHTML);
    };

</script>
</body>

2.對於後生成事件的綁定,能夠用事件委託app

<body>
    <button id="btn">增長</button>
    <ul id="ul1">
        <li>001</li>
        <li>002</li>
        <li>003</li>
        <li>004</li>
        <li>005</li>
    </ul>

    <script>
        var oUl = document.getElementById('ul1');
        var aLi = oUl.getElementsByTagName('li');
        var oBtn = document.getElementById('btn');
        oUl.onclick = function (e) {
            console.log(e.currentTarget);//this
            console.log(e.target);//事件源
            };

        oBtn.onclick = function () {
            var oLi = document.createElement('li');
            oLi.innerHTML = Math.random();
            oUl.appendChild(oLi);
        };

    </script>
</body>
e.currentTarget=this  
e.target獲取事件源  
能夠經過e.currentTarget和e.target的比較得知是否是由事件冒泡觸發的

總結:事件模型/事件冒泡/事件委託:利用事件冒泡,把子元素委託給父元素綁定dom

相關文章
相關標籤/搜索