为什么用.each()遍历jQuery对象不能给我jQuery对象? [英] Why does iterating over jQuery objects with .each() not give me jQuery objects?

查看:92
本文介绍了为什么用.each()遍历jQuery对象不能给我jQuery对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下按预期工作:

$(".foo").first().text("hi!")

...因为 first() 返回jQuery对象.

...because first() returns a jQuery object.

但是,如果我想使用 text() 方法进行所有匹配,我需要要做:

However, if I want to work with the text() method for all matches, I need to do:

$(".foo").each( function(idx, obj) {
  $(obj).text("hi!")
  }
)

...因为 each() 为您提供了DOM对象.

...because each() gives you DOM objects.

这种令人困惑的差异背后的设计原因是什么?如何避免每次比赛都必须构建jQuery对象?

What is the design reason behind this baffling difference? How can I avoid having to build a jQuery object for each match?

推荐答案

可能是由于与循环大型集合有关的性能原因?如果只需要DOM对象,则可以节省周期.如果您需要jQuery对象,则可以轻松获得它.

Possibly due to performance reasons related to looping over large collections? If you only need the DOM objects, then you save cycles. If you need the jQuery object, then you can easily get that.

我通常不向每个参数提供第二个参数,因此我可以使用$(this).

I typically don't provide the 2nd parameter to each, so I can use $(this).

这篇关于为什么用.each()遍历jQuery对象不能给我jQuery对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆