event delegation

Event delegation is often asked in interviews.

For example the following code

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

Now the question comes? How to efficiently bind events to the li element so that when the user clicks the li element, the content in the li element can be prompted?

If this is done with JQUERY, it's a good solution

$(function(){

     $("li").on("click",funcition(){

          alert($(this).text()); or write alert($(this).html());

        }

    })

 

But the original idea to write in native JS is:

window.onload = function() {

var ul = document.getElementById("ul");

var lis = ul.getElementsByTagName("li");

for(var i = lis.length-1;i>=0;i--) {

  lis[i].onclick = function() {

         alert(this.innerHTML);

          }

     }

 

        }

This idea is the simplest and most intuitive and correct, but there are certain problems, when the li in the DOM

When there are many elements, the binding operation of such loop traversal is bound to take up a lot of resources.

We can use some features of the event to bind the operation to the ul element, and get it automatically when the event is triggered

The object of the current event operation, and then complete the operation, look at the following code:

window.onload = function(){

 

 

 

    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324829463&siteId=291194637