[英]Do looping through items and adding handlers to it hurt performance
當我遍歷列表項並向所有單獨的項添加點擊處理程序時,它是否會影響性能?
我這樣做的原因是因為我只想讓列表項在包含超鏈接的情況下可點擊。
我目前使用的代碼是:
$('ul.paginator li').each(function() {
if ($('a', this).length > 0) {
$(this).css('cursor', 'pointer');
$(this).click(function() {
location.href = $('a', this).attr('href');
});
}
});
我不確定它對性能的影響有多大,但是您是否考慮過使用稍微簡化的 jQuery 選擇器:
$('ul.paginator li:has(a)').each(
function(){
$(this).css('cursor','pointer').click(
function(){
location.href = $(this).find('a').attr('href');
});
});
順便說一句,性能取決於您搜索的元素數量,而不是其他任何東西。 只是幾個,它可能是難以察覺的,幾千個,它(可能)會很明顯。
編輯以減少has()
的費用:
$('ul.paginator li a').each(
function(){
var address = this.href;
$(this).closest('li').css('cursor','pointer').click(
function(){
location.href = address;
});
});
這應該更便宜,因為它只會選擇li
a
元素,然后向上移動以影響該li
元素。
是的,最好將delegate
與適當的選擇器一起使用,該選擇器僅選擇您想要的項目。
將只創建和附加一個處理程序。
如果您不想使用has()
就足夠了(不需要多個處理程序):
$('ul.paginator').delegate('click', 'li', function() {
var link = $('a', this);
if (link.length > 0) {
location.href = link.attr('href');
}
});
取決於有多少行。 如果有數千個,那么是的。 如果有適度的數量,那么還不足以引起注意。
另一種方法是將點擊處理程序放在包含項目的元素上,然后當點擊事件進入時,使用傳遞給處理程序的事件中的數據來確定要做什么。 一名處理人員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.