addEventListener和jquery on有什么区别? [英] Difference between addEventListener and jquery on?

查看:540
本文介绍了addEventListener和jquery on有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图捕获页面上的所有点击事件.

So I am trying to capture all the click events on a page.

我可以用这个

window.addEventListener('click', function(e){
    console.log(e.target);

}, true);

$("*").delegate("*", "click", function(e){
    if (e.target === this) {
        console.log(e.target);
    }
});

有什么区别?

推荐答案

实际上有一些区别:

  1. 您不能对jQuery .on()使用捕获,这种情况根本不存在. jQuery仅支持事件冒泡.但是,您可以使用.addEventListener()

  1. You can't use capture for jQuery .on(), such a thing just doesn't exist. jQuery only supports event bubbling. You could, however, specify whether to capture the event in capture phase or bubble phase with .addEventListener()

jQuery .on()允许您为多个事件附加相同的事件侦听器,而.addEventListener仅允许您一次将事件侦听器添加至单个事件类型(尽管您可以使用类似

jQuery .on() allows you to attach the same event listener for multiple events, whereas .addEventListener only allows you to add an event listener to a single event type at a time (although you could use something like

["event type 1", "event type 2"].forEach( function(i){ 
        element.addEventListener(i, function(){} ); 
})

但这很混乱)

也许您会认为.on()和.addEventListener()都将事件侦听器添加到事件目标;它不是那么简单,至少对于jQuery来说不是.除此之外,请有人补充细节,因为我也不很清楚:P

Maybe you would think that both .on() and .addEventListener() adds event listeners to an event target; it's not that simple, at least not for jQuery. More on that, someone add in details please, because I'm not very clear either :P

使用.on()附加的事件侦听器可以通过调用另一个jQuery函数.trigger()来调用,但是使用.addEventListener()附加的事件侦听器将 not 响应.trigger()

Event listeners attached by using .on() can be invoked by calling .trigger(), another jQuery function, but event listeners attached by using .addEventListener() will not respond to .trigger()

这篇关于addEventListener和jquery on有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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