$('#SomeSelectorID').find('.SomeElementsByClassName').each(function () {
$(this).some code here;
$(this).some other code there;
$(this).some other code here and there;
});
如果我在循环的顶部写入 var TheThis = $(this); 然后将 $(this) 替换为 TheThis这真的是性能优化吗?
最佳答案
这是一个明确的性能优化。一个你可能不会注意到,但没有理由不去做。
您示例中的代码意味着 DOM 将被询问 3 次以查找 $(this) 元素,然后对其执行操作。将它缓存在一个变量中意味着它只会发生一次。
$('#SomeSelectorID').find('.SomeElementsByClassName').each(function () {
var $this = $(this);
$this.some code here;
$this.some other code there;
$this.some other code here and there;
});