通过性能将事件处理程序附加到jQuery中的元素的最佳方式 [英] best way to attach an event handler to element in jQuery by performance

查看:104
本文介绍了通过性能将事件处理程序附加到jQuery中的元素的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过性能,将事件处理程序附加到jQuery中的元素的最佳方法是什么?

我要附加的所有元素事件处理程序是静态的
,我们没有任何生成和动态创建的元素:

All elements that I want to attach an event handler to them, are static and we don't have any generated and dynamically created elements:

<div class="foo"></div>
<div class="bar"></div>
<div class="qux"></div>

我想附加点击事件处理程序我们有三个选择。

I want to attach click event handler to all them separately, I have three options.

在这种经典方法中,我将直接将事件处理程序附加到元素:

In this classic method, I will attach the event handler directly to the elements:

$('.foo').on('click', f);
$('.bar').on('click', g);
$('.qux').on('click', h);






II。将事件处理程序多次附加到父级



在这种方法中,我将把每个元素的事件处理程序多次附加到父对象:


II. Attaching event handler to parent multiple times

In this method, instead of previous one, I'll attach the event handler to a parent one, multiple times, for each element:

$('body').on('click', '.foo', f);
$('body').on('click', '.bar', g);
$('body').on('click', '.qux', h);






III。将事件处理程序附加到父项只需一次



此方法与上一个方法类似,除了一个区别。
我将附加事件处理程序一次,我将检查处理程序本身的
所需的选择器:


III. Attaching event handler to parent just one time

This method is just like previous method, except one difference. I'll attach the event handler only one time, and I will check the desired selectors in the handler itself:

$('body').on('click', function (e) {
    var $elem = $(e.target);

         if ($elem.is('.foo')) { f(); }
    else if ($elem.is('.bar')) { g(); }
    else if ($elem.is('.qux')) { h(); }
});






我想知道哪一个是最好的表现?


I want to know which one is the best as performance?

推荐答案

决定将其从评论移到回答。

IMO,事件绑定的操作不会影响性能。应该考虑的是操作,即在处理程序中执行。这就是为什么第三个选项可能是最差的。

第二个选项,AFAIK通常用作事件委托。大多数情况下,如果要将事件绑定到将要创建的元素,即通过AJAX:

The second option, AFAIK, is commonly used as event delegation. Mostly, in cases when you want to bind an event to the element, that would be created in the future, i.e. via AJAX:

$(document).on('click', '.futureElement', alert);
$.post("someurl", {data: someData}, function () {
   //create element with class .futureElement
});

第一个是jQuery绑定事件的常见方式,因此是最快的一个。

The first one is the common way of binding event with jQuery, therefore the fastest one of the presented.

这篇关于通过性能将事件处理程序附加到jQuery中的元素的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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