使用文档和元素进行事件触发之间的区别 [英] Difference between using document and element for on event trigger

查看:96
本文介绍了使用文档和元素进行事件触发之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在事件触发器上给出这两个jquery

Given these two jquery on event triggers

$(document).on("click", "a[data-trigger='colorbox']",function(e){

$("a[data-trigger='colorbox']").on("click",function(e){

在我使用第一个颜色框之前,我必须单击锚标记两次.对于后续点击,不需要第二次点击即可触发.但是对于第二个,第一次单击就会触发颜色框.两者之间有什么区别吗?

I had to click on the anchor tag twice before the colorbox is triggered when I used the first one. For subsequent clicks, it doesnt require a second click to trigger. But for the second one, the colorbox is triggered on the very first click. Is there any difference between the two?

我对该函数的内容如下

e.preventDefault();
var currentTarget = $(e.currentTarget);
currentTarget.colorbox({inline : true, href : currentTarget.data("href")});

推荐答案

$(document).on("click", "a[data-trigger='colorbox']",function(e){

这会将click事件绑定到文档及其中的所有子元素.然后,此click事件检查clicked元素是否与过滤器a[data-trigger='colorbox']

This binds a click event to the document and all child elements within it. This click event then checks if the clicked element matches the filter a[data-trigger='colorbox']

稍后:

$("a[data-trigger='colorbox']").on("click",function(e){

将点击事件直接绑定到a[data-trigger='colorbox'].

binds the click event to the a[data-trigger='colorbox'] directly.

现在,如果您的元素是动态的,那么您将要使用第一个元素.因为这意味着您不必继续重新绑定您的click事件.如果您的元素是静态的,那么您希望使用后者,因为它效率更高.

Now if your element is dynamic you would want to use the first one. As this means you don't have to keep rebinding your click event. If your element is static then you want to use the later as it's more efficient.

第三种方法(或更有效的选择第一种方法)是将其绑定到与document相对的静态 parent 元素,然后对被单击的元素进行过滤,即

A third way (or a more efficientway to do the first option) is to bind this to a parent element that is static as opposed to the document and then filter on the element being clicked, i.e.

$(parent).on("click", "a[data-trigger='colorbox']",function(e){

效率更高,因为它不需要捕获整个文档上的点击事件

this is more efficent because it does not need to capture click events on the entire document

这篇关于使用文档和元素进行事件触发之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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