我正在升级一个包含 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/