javascript - 什么是最有效的事件声明方式?

标签 javascript jquery jquery-events

我正在升级一个包含 2 个包含大量元素的 View 的 Web 项目。

此时,所有元素都有几个事件,如mouseenter, mouseleave, click, ... 定义了一个在网页渲染期间逐一

我的问题是:使用最后一个 jQuery 方法是否更有效 .on()使用这样的事件映射和动态选择器:

$("#main-container").on({
    mouseenter: function (event) {    
       //Do stuff
    },            
    mouseleave: function (event) {
       //Do stuff     
    },
    mousedown: function (event) {
       //Do stuff
    }
    },
    ".cartridge"
);

比当前事件声明:

$('[id^="cartridge"]').each(function(index) {       
    $(this).click(function(){
        //Do stuff
    }); 
    $(this).mouseenter(function(){
        //Do stuff
    }); 
    $(this).mouseleave(function(){
        //Do stuff
    }); 
});

最佳答案

根据 .on() 的 jquery API,它更有效,因为只有一个事件附加到您的#main-container,而来自不同 .cartridge 的事件只需要“冒泡”到这个容器。

来自 jquery API:

In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:

$("#dataTable tbody tr").on("click", function(event){
  alert($(this).text());
});

A delegated-events approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

$("#dataTable tbody").on("click", "tr", function(event){
  alert($(this).text());
});

http://api.jquery.com/on/查看“直接和委托(delegate)事件”

关于javascript - 什么是最有效的事件声明方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12471396/

相关文章:

jquery - 如何从类名中读取值

javascript - 如何对 div 内的所有内容(除了一个特定的 div 及其子节点)进行单击事件?

javascript - 对象键顺序

javascript - 在 div 中的特定 <a> 上应用 CSS

javascript - live.js 与 prefixfree 结合使用时不会重新加载 css

IE 中的 JavaScript : 'this' keyword refers to window object (? )

javascript - 具有淡入淡出效果的全背景图像

jquery foreach循环中的javascript函数不等待响应

javascript - 如何使用 onclick 将文本内容获取到单元格的变量

javascript - 触发了错误的类