简体   繁体   中英

Javascript performance - Iterating over dom and adding listeners

I am currently working in a big web project where we have lots of dom elements which need a listener for click/change/... events. The first 500 lines of code of the main javascript file look like this.

$( ".bla" ).each(function(e) {
    $(this).on("click", function(){
        ... 
    });
});

So basically we add like 100 listeners and for each listener we have to iterate over the complete dom tree. I think this will take up considerable computation power. Is there something like a best practice solution to avoid this?

You can use event delegation:

$(document).on("click", ".bla", function(){
  // ...
});

Hopefully you learned from the other answers that there was no need to use each . However, there may not even be a need to select all elements with class .bla as in your example.

Rather, if a div, or some other element, contains all of the elements for which you are interested in handling a click event, you can put the event listener on the container , and then you determine which element got clicked by inspecting the target property of the event. This works due to 'event propagation' -- if not handled directly handled on the element you clicked, the event will propagate up the DOM.

Simple example below with just two buttons. This is straight Javascript which should easily enough be converted to JQuery -- hope it helps.

<html>
<head>
    <script>
        setTimeout(function() {
            document.getElementById('container').addEventListener('click', function(event) {
                alert('You clicked ' + event.target.innerHTML);
            });   
        });
    </script>
</head>
<body>
<div id="container">
    <button id="fooButton" type="button">foo</button>
    <button id="barButton" type="button">bar</button>
</div>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM