Event delegation in jQuery, how to do it?

荒凉一梦 提交于 2019-11-28 02:25:37

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.

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

Scott Selby

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.

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