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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:50:02  来源:igfitidea点击:

jQuery ,each() - return value

javascriptjquery

提问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 iargument on the function you're giving each, don't return anything from the eachfunction, and don't assign the result of eachto 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 eachis a closure over iand so can access and update it directly. By declaring ias an argument of the eachcallback, you were dealing with a different ion each iteration (the one that jQuery passes in, which is the index of the element in the set). And separately, the return value of eachis the jQuery object on which you call it (docs), which clearly isn't what you want.

这样,您传入的函数each就是一个闭包i,因此可以直接访问和更新它。通过声明ieach回调的参数,您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 wvariable as local to the eachcallback, because I'm assuming you don't have a wvariable 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 的牺牲品。