AddiEventListener (type, fn, true/false) binds event's third parameter function and uses event bubbles to achieve event delegation

Keywords: Attribute Javascript JQuery

(1):

The first parameter type, the type of event, such as click, mouseover, etc.

fn, the function of event monitoring execution;

The third parameter is the process of determining the execution of events. First, let's look at a picture:

From the pictures, we can see that the event is captured before bubbling, and the third parameter determines whether to capture or bubbles first. If true, it is captured, or bubbles anyway. Let's take an example:

html:

<ul id="ul">
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
    <li>4444</li>
</ul>

javascript:

 var ul = document.querySelector('#ul');
 ul.addEventListener('click' ,function () {
     alert('ul')
 },false);

 var li = document.querySelector('#ul > li');
 li.addEventListener('click' ,function () {
     alert('li')
 },true)

In the example above, the execution process of listening for Li events is capture, and capture precedes bubble execution, so alert (''li') is first followed by alert (''li').
alert (''ul'), but if we change it like this:

var ul = document.querySelector('#ul');
ul.addEventListener('click' ,function () {
     alert('ul')
 },true);

var li = document.querySelector('#ul > li');
li.addEventListener('click' ,function () {
    alert('li')
},true)

The result is alert (`ul') and alert (`li').

(two):

Or the example above, if we want to implement point li binding events, such as clicking to change the background, we might normally write code like this:

var li = document.querySelectorAll('#ul > li') ;
for ( var i = 0 ; i < li.length ; i++ ){
     li[i].index = i;
     li[i].onclick = function () {
         this.style.background = 'red';
     }
 }

Of course, this is not a problem, but if Li is very large, it will be much more convenient to use event bubbles. The implementation method is to bind events on the parent element of li:

 var ul = document.querySelector('#ul');
 ul.addEventListener('click' ,function (e) {

      var ev = e || event ;
      var li = ev.target;
      li.style.background = 'blue';
      console.log(ev.currentTarget);//The object of event monitoring, ul
 },false);

Event delegation similar to jquery:

$('#ul').on('click' , 'li' , function(){

    $(this).css('background' , 'blue');
})

Posted by reivax_dj on Sun, 10 Feb 2019 17:18:19 -0800