如果将.on('click'事件)附加到$("body"),性能会受到影响吗? [英] Does performance suffer if I attach .on('click' events to $("body")?

查看:200
本文介绍了如果将.on('click'事件)附加到$("body"),性能会受到影响吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下代码:

$('#loginLink, #registerLink').click(function () {
        dialog(this);
        return false;
    });

$('#detailData')
    .on('click', '.modalDeleteLink, .modalEditLink', function () {
        dialog(this);
        return false;
    })

#loginLink和#registerLink中只有一个,但是类.modalDeleteLink和.modalEditLink最多可以包含一百个元素.

There are just one of #loginLink and #registerLink but there could be up to a hundred elements with the classes .modalDeleteLink and .modalEditLink.

我正在考虑更改所有这些元素,因此它们具有一类.dialogLink,然后仅使用以下代码:

I was thinking to change all of these elements so they have a class of .dialogLink and then just using the following code:

$("body").on("click", ".dialogLink", function(){
   dialog(this);
   return false;
});

此代码易于维护.但是,将其附着在身体上会不会有性能上的劣势?

This code is a lot easier to maintain. However would there be any performance disadvantage in attaching this to the body?

推荐答案

除非您有数百个处理程序或非常大的文档,否则您不必担心性能.

You don't need to worry about performance, unless you have hundreds of handlers or extremely large document.

文档中提取:

在大多数情况下,诸如点击之类的事件很少发生,并且效果也不是重要问题.但是,诸如鼠标移动或滚动之类的高频事件每秒可能触发数十次,在这种情况下,明智地使用事件变得更加重要.可以通过减少处理程序本身中的工作量,缓存处理程序所需的信息(而不是重新计算信息)或通过使用setTimeout限制实际页面更新的速率来提高性能.

In most cases, an event such as click occurs infrequently and performance is not a significant concern. However, high frequency events such as mousemove or scroll can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using setTimeout.

在文档树顶部附近附加许多委派的事件处理程序会降低性能.每次事件发生时,jQuery必须将该类型所有附加事件的所有选择器与从事件目标到文档顶部的路径中的每个元素进行比较.为了获得最佳性能,请在尽可能靠近目标元素的文档位置附加委托事件.避免在大型文档上的委派事件中过度使用document或document.body.

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.

这篇关于如果将.on('click'事件)附加到$("body"),性能会受到影响吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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