我想学习一些关于优化我的 jQuery 代码的知识...
有没有办法改进下面的代码,让变量 $selected 在函数外声明,但仍然可以访问,这样就不会每次都遍历 DOM?
或者这段代码是否已尽可能优化?
或者...我想我可能误解了 jquery DOM 遍历发生的方式和时间。
$('#full-width-layout_c1_col-1-1_1').on(
'mouseenter mouseleave click',
'a.project_open, a.song_open',
function(e) {
var $selected = $(this).closest('tr').find('div');
if (e.type == 'mouseenter') {
$selected.addClass("hovered");
}
else if (e.type == 'mouseleave'){
$selected.removeClass("hovered");
}
else if (e.type == 'click'){
$selected.addClass('opened');
}
}
);
最佳答案
如果您希望在 DOM 元素中存储任意数据时获得最后一点性能,请不要使用 jQuery.data()
。那会表现得更好:
var $selected = this.closestdiv;
if(!$selected) { // first time
$selected = $(this).closest('tr').find('div');
this.closestdiv = $selected;
}
来自这个简单的基准测试 http://jsperf.com/jquerydata/4您可以看到将数据直接存储在 DOM 上比使用 jQuery.data()
快得多。在我的机器上使用 jQuery.data()
比直接存储数据慢 97%。再次,公平警告 - jQuery.data()
有一定的开销,因为它试图对事情变得聪明并防止潜在的内存泄漏。
关于javascript - 如何优化这个简单的 jquery 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8181963/