我想知道哪种方式在循环中定义函数更好?我总是使用第一种方式。这是对的吗?或者这种情况还有另一种方法?
请指导我,我在代码中经常使用第一种方式,我想知道这是真的吗?
$('.elements').each(function(){
// elements
var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
// variables
var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
function doSomething(){
$t.width($anotherEl.width() + $anotherEl2.width());
// other codes ...
}
doSomething();
$(window).resize(doSomething);
});
或
function doSomething(par1, par2, par3, par4){
var $t = par1 , $anotherEl = par2, $anotherEl2 = par3;
$t.width($anotherEl.width() + $anotherEl2.width());
// other codes ...
}
$('.elements').each(function(){
// elements
var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
// variables
var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
doSomething($t, $anotherEl, $anotherEl2, isLand);
$(window).resize(function(){
doSomething($t, $anotherEl, $anotherEl2, isLand);
});
});
感谢您的提前。
最佳答案
为什么要循环执行此操作?因为这可以在不使用循环的情况下完成,例如:
function doSomething(){
$('.elements').each(function(){
// elements
var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
// variables
var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
// now do something with the vars here.
});
}
$(window).resize(doSomething).resize(); // <---trailing .resize() triggers on dom ready.
<小时/>
我发现您的方法存在的问题是:
- 使用
.each()
循环一次又一次地定义相同的函数,在每次迭代中执行相同的函数并绑定(bind)resize
事件。 - 第二个似乎好一点,但部分原因是
.resize
绑定(bind)。
关于javascript - 在循环中定义函数的最佳方法是什么? - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35407783/