jQuery中的事件委托,该怎么做? [英] Event delegation in jQuery, how to do it?

查看:108
本文介绍了jQuery中的事件委托,该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我曾经这样使用事件委托:

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);

在jQuery中这等效吗?我知道 .on(),但是如何在事件委托中使用它?我的意思是这是怎么做到的:

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 ..
      }      
});

但是不是和普通JavaScript一样吗?我想知道是否有更好的方法来实现它,如果这是唯一的方法,那么与JS相比,jQuery的好处是什么?一个?

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 ?

推荐答案

您可以执行以下操作:

$(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 ..
});




但是这与香草JavaScript一样吗?我想知道是否有更好的方法来实现。而且如果这是唯一的方法,那么jQuery相对于JS的好处是什么?

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 ?

当然,它基本上是相同的,jQuery只是通过提供围绕DOM API的包装使您的生活变得更轻松,但这并不会改变DOM的工作方式。

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.

但是有一个区别,即 this 将引用选择器匹配的元素,而不是处理程序绑定到的元素。

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.

通常,优点是与使用 addEventListener 相比,jQuery代码与跨浏览器的兼容性更高。

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

这篇关于jQuery中的事件委托,该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆