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

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

jQuery each element

jquery

提问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:

也可以看看:

回答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 $.eachreturns the collection you're iterating.

是的,可以链接,因为$.each返回您正在迭代的集合。

$.each($("p"), function() { $(this).css("color", "green") }).addClass('test');

回答by FishBasketGordo

$.eachrequires two parameters, the second being a callback that executes once for each element. If you don't pass the callback parameter, $.eachwon't work.

$.each需要两个参数,第二个是对每个元素执行一次的回调。如果不传递回调参数,$.each将无法工作。

Also, $.eachreturns 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 eachis needed to achieve the (most likely) desired effect.

请注意,不需要任何版本each来实现(最有可能的)预期效果。

$("p").css("color", "green");

does the job.

做这项工作。