javascript jQuery ,each() - 返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6483420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery ,each() - return value
提问by Darkry
I have this code:
我有这个代码:
i = 60;
i = $(this).find('li a').each(function(i) {
w = $(this).text();
$('#js').text(w);
w = $('#js').width();
if(w > i) {
i = w;
}
return i;
});
It's wrong :-). I have X strings ($(this).find('li a')). And i want to get the length (px) of the longest one and save its length to variable i. That i will use later in my code.
这是不对的 :-)。我有 X 个字符串 ($(this).find('li a'))。我想获得最长的长度(px)并将其长度保存到变量 i。我稍后会在我的代码中使用它。
Thank you and i'm sorry for my English :-)
谢谢你,我为我的英语感到抱歉:-)
回答by T.J. Crowder
Don't declare an i
argument on the function you're giving each
, don't return anything from the each
function, and don't assign the result of each
to i
. Then it should work.
不要i
在您提供的函数上声明参数each
,不要从each
函数返回任何内容,也不each
要将结果分配给i
。那么它应该工作。
i = 60;
$(this).find('li a').each(function() {
var w = $(this).text();
$('#js').text(w);
w = $('#js').width();
if(w > i) {
i = w;
}
});
That way, the function you're passing into each
is a closure over i
and so can access and update it directly. By declaring i
as an argument of the each
callback, you were dealing with a different i
on each iteration (the one that jQuery passes in, which is the index of the element in the set). And separately, the return value of each
is the jQuery object on which you call it (docs), which clearly isn't what you want.
这样,您传入的函数each
就是一个闭包i
,因此可以直接访问和更新它。通过声明i
为each
回调的参数,您i
在每次迭代中处理不同的(jQuery 传入的,它是集合中元素的索引)。另外, 的返回值each
是您调用它的 jQuery 对象 ( docs),这显然不是您想要的。
More about closures, if you're not clear on them: Closures are not complicated
更多关于闭包的信息,如果你不清楚的话:闭包并不复杂
In the code above, I also declared the w
variable as local to the each
callback, because I'm assuming you don't have a w
variable outside of it you want updated and so were falling prey to The Horror of Implicit Globals.
在上面的代码中,我还将该w
变量声明为each
回调的局部变量,因为我假设您w
在它之外没有想要更新的变量,因此会成为The Horror of Implicit Globals 的牺牲品。