高性能 javaScript 之事件委託

開卷有益,做一個精益求精的開發者!

 

事件委託

使用前提:當頁面存在大量元素,且每個元素都要一次或多次綁定事件(如點擊事件)。

使用原因:事件綁定佔用處理時間,瀏覽器會跟蹤每個事件處理,會佔用更多內存。

解決辦法:使用事件委託。

 

示例代碼:

<!DOCTYPE html>
<html>
<head>
    <title>事件委託</title>
    <style>
        div{
            border:1px solid #999;
            padding:20px;
        }
        div.box{
            width:100px;
            height:100px;
            line-height: 100px;
            cursor: pointer;
            background: #ccc;
            margin:10px;
            color:#f7f7f7;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="root" class="root">
        <div class="box click3">click3事件</div>

        <div class="content">
            <div class="box click2">click2事件</div>

            <div class="article">
                <div class="box click1">click1事件</div>
            </div>
        </div>
    </div>

    <script>
        //點擊事件
        function fn1(){
            console.log("您觸發了click1事件!");
        };

        function fn2(){
            console.log("您觸發了click2事件!");
        };

        function fn3(){
            console.log("您觸發了click3事件!");
        };

        //事件委託
        //避免了在所有需要綁定事件的元素上綁定事件處理,僅在其最外層元素上使用事件委託。
        document.getElementById("root").οnclick=function(e){
            console.log("事件委託");
            //瀏覽器兼容
            e = e||window.event;
            var target = e.target || e.srcElement;
            console.log(target);
            console.log(target.className);

            //先判斷是哪個目標元素,再觸發對應的事件。
            //注意按照冒泡規則確定判斷順序,先判斷內層元素。
            //注意class有多個的情況。也可以用target.id,但不建議使用。
            if(target.className == 'box click1'){
                fn1();
            }else if(target.className == 'box click2'){
                fn2();
            }else if(target.className == 'box click3'){
                fn3();
            }else{
                //沒有符合的目標元素,退出。
                return
            }
        }
</script>
</body>
</html>

 

測試

數字爲點擊順序

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章