jQuery - 从数组中获取元素作为 jQuery 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17437500/
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-26 19:03:46  来源:igfitidea点击:

jQuery - Get element from array as jQuery element?

javascriptjquerydomword-wrap

提问by jan

If I call

如果我打电话

$(".myClass")

I get an array of elements. If I now want to get the first element as jquery element I would do something like this:

我得到一个元素数组。如果我现在想将第一个元素作为 jquery 元素,我会这样做:

$($(".myClass").get(0))

So I wrap the DOM-Element, which I get from the array again with the jQuery operator. Is there a more elegant way to do this? Some get method, which returns a jQuery element for example?

所以我包装了 DOM-Element,我再次使用 jQuery 运算符从数组中获取它。有没有更优雅的方法来做到这一点?一些 get 方法,例如返回一个 jQuery 元素?

回答by nnnnnn

Use the eq()method:

使用eq()方法

$(".myClass").eq(0)

This returns a jQuery object, whereas .get()returns a DOM element.

这将返回一个 jQuery 对象,而.get()返回一个 DOM 元素。

.eq()lets you specify the index, but if you just want the first you can use .first(), or if you just want the last you can use (surprise!) .last().

.eq()允许您指定索引,但如果您只想要第一个可以使用.first(),或者如果您只想要最后一个可以使用 (惊喜!) .last()

"I get an array of elements."

“我得到了一组元素。”

No you don't, you get a jQuery object which is an array-like object, not an actual array.

不,你没有,你得到一个 jQuery 对象,它是一个类似数组的对象,而不是一个实际的数组。

If you plan to use jQuery much I suggest spending half an hour browsing through the list of all methods.

如果您打算大量使用 jQuery,我建议您花半个小时浏览所有方法列表