Home > Web Front-end > JS Tutorial > Explain JavaScript event delegation technology

Explain JavaScript event delegation technology

高洛峰
Release: 2016-11-25 14:20:54
Original
969 people have browsed it

Before explaining, let’s talk about performance.

If there are a large number of buttons in a whole page, we have to bind event handlers to each button. This will affect the performance.

First of all, each function is an object , the object will occupy a lot of memory. The more objects in the memory, the worse the performance.

Secondly, the increase in the number of dom accesses will lead to delayed page loading. In fact, there are still some problems in how to make good use of event handlers. A very good solution.

1. Event Delegation

The solution to the problem of too many event handlers is event delegation technology.

Event delegation technology uses event bubbling. Just specify one event handler.

We can bind event handlers for a parent element that needs to trigger an event.

HTML code:

<ul id="mylist">
        <li id="li_1">sdsdsd</li>
        <li id="li_2">sdsdsd</li>
        <li id="li_3">sdsdsd</li>
</ul>
Copy after login

Now we have to bind event handlers for these 3 li...

Just need to ul binding event handler.

js code:

obj.eventHandler($("mylist"),"click",function(e){
                    e = e || window.event;
                    switch(e.target.id){    //大家应该还记得target是事件目标,只要点击了事件的目标元素就会弹出相应的alert.
                        case "li_1":
                        alert("li_1");
                        break;
                        case "li_2":
                        alert("li_2");
                        break;
                        case "li_3":
                        alert("li_3");
                        break
                    }
                })
Copy after login

If in a complex web application, this kind of event delegation is very practical.

If you don’t use this method, go one by one Binding means countless event handlers.

Okay. That’s it for now.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template