jQuery 每个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9009494/
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 element
提问by Ryre
I'm curious why this code is invalid:
我很好奇为什么这段代码无效:
$.each( $("p") ).css("color", "green");
While this code works fine:
虽然此代码工作正常:
$.each($("p"), function() { $(this).css("color", "green") });
Is it not possible to chain elements with each?
不能将每个元素链接起来吗?
回答by Rob W
Remove the wrapper:
移除包装:
$("p").css("color", "green");
If you want to use $.each
, specify a function as a second argument:
如果要使用$.each
,请指定一个函数作为第二个参数:
$("p").each(function() {
//Or: $.each( $("p"), function() {
$(this).css("color", "green");
});
The jQuery method automatically returns an instance of the collection, so chaining should still be possible.
jQuery 方法会自动返回集合的一个实例,因此链接应该仍然是可能的。
Demo: http://jsfiddle.net/pC2Bj/
演示:http: //jsfiddle.net/pC2Bj/
See also:
也可以看看:
- jQuery docs -
$().each()
- jQuery docs -
$.each
- jQuery 文档 -
$().each()
- jQuery 文档 -
$.each
回答by Ryre
$.each()
requires a function as the second argument. You've only passed one argument.
$.each()
需要一个函数作为第二个参数。你只通过了一个参数。
http://api.jquery.com/jquery.each/
http://api.jquery.com/jquery.each/
jQuery.each( collection, callback(indexInArray, valueOfElement) )
collectionThe object or array to iterate over.
callback(indexInArray, valueOfElement)The function that will be executed on every object.
jQuery.each( 集合,回调(indexInArray, valueOfElement) )
collection要迭代的对象或数组。
callback(indexInArray, valueOfElement)将在每个对象上执行的函数。
Yes, it is possible to chain, since $.each
returns the collection you're iterating.
是的,可以链接,因为$.each
返回您正在迭代的集合。
$.each($("p"), function() { $(this).css("color", "green") }).addClass('test');
回答by FishBasketGordo
$.each
requires two parameters, the second being a callback that executes once for each element. If you don't pass the callback parameter, $.each
won't work.
$.each
需要两个参数,第二个是对每个元素执行一次的回调。如果不传递回调参数,$.each
将无法工作。
Also, $.each
returns the object over which it iterates, so chaining doesn't work like it would with methods that return a jQuery object.
此外,$.each
返回它迭代的对象,因此链接不像返回 jQuery 对象的方法那样工作。
回答by MaxH
Note that no version of each
is needed to achieve the (most likely) desired effect.
请注意,不需要任何版本each
来实现(最有可能的)预期效果。
$("p").css("color", "green");
does the job.
做这项工作。