Home > Web Front-end > JS Tutorial > body text

javascript event delegation and jquery event delegation

hzc
Release: 2020-07-01 09:46:50
forward
2027 people have browsed it

After New Year’s Day, the first article of the New Year.
Original Intention: Many interviews will involve event commissioning. I have read many blog posts one after another. They are all very good and each has its own merits. I have to think about it myself, for my own review in the future, and at the same time To provide front-end partners who are looking for a job with a seemingly more comprehensive place to interpret event delegation to understand its principles, this article summarizes two versions of event delegation: javascript, jquery;

Definition of event delegation:

Use event bubbling, onlyspecify an event handler to manage all events of a certain type.

Advantages of event delegation:

  • The number of event handlers added to the page in js directly affects the running performance of the web page. Because each event processing function is an object, the object will occupy memory, and the more objects in the memory, the result will be worse performance; and the more times the DOM is accessed, it will cause the structure to be redrawn or redrawn. The number of rows will also increase, which will delay the interactive readiness time of the entire page;

  • For new DOM elements added after the page is processed, event delegation can be used to provide new DOM elements for the new DOM elements. Elements are added and subtracted together with event handlers;

In the following code, the effect to be achieved by the p tag is that the background color changes to red when the mouse clicks on the p tag. The following are js and jq The processing method

    <p>
      </p><p>第一个p</p>
      <p>第二个p</p>
      <p>第三个p</p>
      <p>
          </p><p>这是子集菜单</p>
          <p>我是子集的p
              </p><p>我是子集的p</p>
          
      
    
    <button>点击加一</button>
  
Copy after login

1. js event delegation

If event delegation is not used in js: get all the p tags in the page and then use a for loop to traverse and add event processing functions to each element

let nodes = document.getElementById("nodes");
    let ps = document.getElementsByTagName("p");
    console.log(ps);
    let btn = document.getElementsByTagName("button")[0];
    let inner = 33;

    btn.onclick = function() {
      inner++;
      let p = document.createElement("p");
      p.innerHTML = inner + "新增的p标签啊";
      nodes.appendChild(p);
      console.log(ps);
    };
    for (let i= 0;i<ps.length><p>At this time, after running it in the browser, I tested it and found the result as shown in Figure 1; </p><p><img src="https://img.php.cn/upload/image/376/157/896/1593567746839219.png" title="1593567746839219.png" alt="javascript event delegation and jquery event delegation"></p><p>So how can js be given to new users without event delegation? What about adding event handlers for added tags? The solution is as follows: </p><pre class="brush:php;toolbar:false">let nodes = document.getElementById("nodes");
    let ps = document.getElementsByTagName("p");
    console.log(ps);
    let btn = document.getElementsByTagName("button")[0];
    let inner = 33;

    btn.onclick = function () {
        inner++;
        let p = document.createElement("p");
        p.innerHTML = inner + "新增的p标签啊";
        nodes.appendChild(p);
        addEvent();//将新dom元素增加到页面后再执行循环函数
        console.log(ps);
    };

    function addEvent() {
        for (let i = 0; i <p>At this time, the browser runs as shown in Figure 2:</p><p><img src="https://img.php.cn/upload/image/129/624/157/1593567770605067.png" title="1593567770605067.png" alt="javascript event delegation and jquery event delegation"></p><p>At this time, although adding events for new dom elements is solved There is a problem with the processing function, but after careful consideration, its performance has declined compared to before. The reason is that another event processing function (object) has been added, which once again takes up memory; therefore, events will be used at this time Delegation, the advantages of event delegation are also reflected at this time: </p><pre class="brush:php;toolbar:false">let nodes = document.getElementById("nodes");
    let ps = document.getElementsByTagName("p");
    console.log(ps);
    let btn = document.getElementsByTagName("button")[0];
    let inner = 33;

    btn.onclick = function () {
        inner++;
        let p = document.createElement("p");
        p.innerHTML = inner + "新增的p标签啊";
        nodes.appendChild(p);
        console.log(ps);
    };
//事件委托,为nodes指定一个事件处理函数,处理nodes下为p标签的所有元素的cilck事件
    nodes.onclick= function(e){
        let ev = e || window.event
        let target = ev.target || ev.srcElement //srcElement IE浏览器
        //这里要判被处理元素节点的名字,也可以增加相应的判断条件 target.nodeName.toLowerCase() == 'p'||target.nodeName.toLowerCase() == 'span',但是要注意不要使用父级元素的名称,因为再点击子元素之间的空气的时候,由于事件冒泡他会给父级元素也增加相应的事件处理函数;因为返回的节点名称一般都是大写,所以这时要用toLowerCase()处理一下;
        if(target.nodeName.toLowerCase() == 'p'){ 
            target.style.background = 'green'
        }
    }
Copy after login

At this time, the result of running in the browser is shown in Figure 3:

javascript event delegation and jquery event delegation

2 , jquery event delegation:

Compared with js event delegation, the advantages of jquery event delegation: When executing event delegation, only the child element will trigger the event function, and the parent element executed on its behalf will not. The event function will be triggered, so there is no need to judge the name of the element node; (Note that the event delegation method here is on, if the bind method is used, the parent element will trigger the event function)
All nodes under the node here The child nodes labeled p are all assigned event processing functions; the child nodes here can also be multiple similar to 'p, span'. It should be noted that the same labels as nodes cannot be written here, otherwise the intervals between click elements The event processing function will be assigned to p under nodes; for example, Example 2:
Example 1:

let inner = 33;
//这里nodes节点下所有标签为p的子节点都被赋予事件处理函数;这里的子节点还可以是多个类似' p,span',需要注意这里面也不可以写同nodes一样的标签,否则点击元素之间的间隔会给nodes下的p赋予事件处理函数
$('#nodes').on('click','p',function(e){
        let target = $(e.target)
        target.css('backgroundColor','red')
    })
    $('button').click(()=>{
        inner++;
        $('#nodes').append($('<p>我是新增加的p标签'+inner+'</p>'))
    })
Copy after login

The effect of browser operation is shown in Figure 4:

javascript event delegation and jquery event delegation

##Example 2:

    <p>
        </p><p>第一个p</p>
        <p>第二个p</p>
        <p>第三个p</p>
        <span>span</span>
        <p>
            </p><p>这是子集菜单</p>
            <p>我是子集的p
                </p><p>我是子集的p</p>
            
        
    
    <button>点击加一</button>

<script>
let inner =33;
$(&#39;#nodes&#39;).on(&#39;click&#39;,&#39;p,p,span&#39;,function(e){
        let target = $(e.target)
        target.css(&#39;backgroundColor&#39;,&#39;red&#39;)
    })
    $(&#39;button&#39;).click(()=>{
        inner++;
        $(&#39;#nodes&#39;).append($(&#39;<p>我是新增加的p标签&#39;+inner+&#39;&#39;))
    })
</script>
Copy after login
The browser running effect is shown in Figure 5:

javascript event delegation and jquery event delegation

Event delegation is not just for processing one type of DOM operation, it can perform functions such as addition, deletion, modification, and query:

js event delegation: different operations

    <p>
        <input>
        <input>
    </p>
    <p>

    </p>

<script></script>
<script>
    let events = document.getElementById(&#39;events&#39;);
    let content = document.getElementById(&#39;content&#39;);
    events.onclick=function(e){
        let ev = e || window.event;
        let target = ev.target || ev.srcElement;
        if(target.nodeName.toLowerCase()==&#39;input&#39;){
            switch(target.id){
                case &#39;addHandle&#39;:
                return addEvent();
                break
                case &#39;deleteHandle&#39;:
                return deleteEvent();
                break
            }
        }
    }
    function addEvent(){
        let add = document.createElement(&#39;p&#39;)
        add.innerHTML = &#39;这是增加按钮&#39;
        content.appendChild(add)
    }
    function deleteEvent(){
        let del = document.createElement(&#39;p&#39;)
        del.innerHTML = &#39;这是删除按钮&#39;
        content.appendChild(del)
    }
</script>
Copy after login

Effects in the browser As shown in Figure 6:

javascript event delegation and jquery event delegation

jquery event delegation: different operations

$('#events').on('click','input',(e)=>{
        let target = $(e.target);
        switch(target[0].id){
                case 'addHandle':
                return addEvent();
                break
                case 'deleteHandle':
                return deleteEvent();
                break
        }
    })
    function addEvent(){
        $('#content').append($('<p>这是增加按钮</p>'))
    }
    function deleteEvent(){
        $('#content').append($('<p>这是删除按钮</p>'))
    }
Copy after login

The effect in the browser is as shown in Figure 7:

javascript event delegation and jquery event delegation

If there is any untruth in this article, I hope the experts will give me some pointers. Discussions are welcome!

Recommended tutorial: "

JS Tutorial"

The above is the detailed content of javascript event delegation and jquery event delegation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jianshu.com
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