High-performance javaScript event delegation

It is beneficial to open the book, and be a developer who strives for perfection!

 

Event delegation

Usage premise: When there are a large number of elements on the page, and each element must be bound to one or more events (such as click events).

Reason for use: Event binding takes up processing time, and the browser will track each event processing, which will take up more memory.

Solution: Use event delegation.

 

Sample code:

<!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>
        //Click event
        function fn1(){             console.log("You triggered the click1 event!");         };

        function fn2(){             console.log("You triggered the click2 event!");         };

        function fn3(){             console.log("You triggered the click3 event!");         };

        //Event delegation
        //Avoid binding event processing on all elements that need to bind events, and use event delegation only on the outermost element.
        document.getElementById("root").οnclick=function(e){             console.log("event delegation");             //Browser compatible             e = e||window.event;             var target = e.target || e. srcElement;             console.log(target);             console.log(target.className);





            //First determine which target element is, and then trigger the corresponding event.
            //Pay attention to determine the order of judgment according to the bubbling rule, and judge the inner elements first.
            //Note that there are multiple classes. Target.id can also be used, but it is not recommended.
            if(target.className =='box click1'){                 fn1();             }else if(target.className =='box click2'){                 fn2();             }else if(target.className =='box click3') {                 fn3();             }else{                 //If there is no matching target element, exit.                 return             }         } </script> </body> </html>












 

test

Numbers are click order

Guess you like

Origin blog.csdn.net/Irene1991/article/details/104699565