Event delegation in jQuery, how to do it?

孤人 提交于 2019-12-17 17:22:36

问题


In JavaScript i used to use event delegation like this :

someDiv.addEventListener('click', function(evt){
    if(evt.target.id == "#someChild"){
       // Do something..
    } else if(evt.target.id == "#anotherChild"){
       // Do something else..
    }
}, false);

What's the equivalent of this in jQuery? i know about .on() but how to use it in event delegation ? i mean is this how is it done :

someDiv.on('click, '#someChild, #anotherChild", function(evt){
      if($(this).is("#someChild")){ 
           // Do something..
      } else if($(this).is("#anotherChild")){
           // Do something else ..
      }      
});

But wouldn't it be just the same as in vanilla JavaScript ? I want to know if there's a better way to achieve it. And if this is the only way, what's the benefit of jQuery way over JS one ?


回答1:


You can do:

$(someDiv).on('click', '#someChild, #anotherChild', function(){
    if(this.id ==='someChild'){ 
       // Do something..
    } else if(this.id === 'anotherChild'){
       // Do something else ..
    }      
});

Or create two event handlers if you do different things for both elements anyway:

$(someDiv).on('click', '#someChild', function(){
     // Do something..    
}).on('click', '#anotherChild', function() {
     // Do something else ..
});

But wouldn't it be just the same as in vanilla JavaScript ? I want to know if there's a better way to achieve it. And if this is the only way, what's the benefit of jQuery way over JS one ?

Of course it's basically the same, jQuery just makes your life a bit easier by providing a wrapper around the DOM API, but it does not change how the DOM works.

There is a difference though, namely that this will refer to the element matched by the selector, not to the element the handler is bound to.

In general, the advantage is that the jQuery code is more cross-browser compatible than using addEventListener.




回答2:


With jQuery you'd do it like this:

function onButtonClick(e) {
  //this = the button that was clicked

}

$(document.body).on('click','button',onButtonClick)

You can read the docs here




回答3:


You could start here, if this element is created dynamically, and not there on page load

$(document).on('click', '#someChild', function(evt) {
   // Do something..      
}); 

If the element is created before the page is rendered then this will work

         <input type="button" onclick="fnClickfn();" id="xxx" />

EDIT:

Oh, also .on only works in later versions on jQuery (I think 1.6 and above), so make sure you aren't using an old version that would require .live and .die.



来源:https://stackoverflow.com/questions/12230057/event-delegation-in-jquery-how-to-do-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!