简体   繁体   English

为什么$(“ ul:first”)。find(“ li”)有效,但是$(“ ul”)[0] .find(“ li”)在jQuery中不起作用?

[英]Why does $(“ul:first”).find(“li”) work but $(“ul”)[0].find(“li”) doesn't work in jQuery?

Does that mean $("ul")[0] is not a jQuery object because it works when I use $($("ul")[0]).find("li") , though it looks a little ugly. 这是否意味着$("ul")[0]不是jQuery对象,因为当我使用$($("ul")[0]).find("li") ,它可以工作,尽管看起来有点难看。

Does anyone have ideas why $("ul")[0] can't be used to find directly? 有谁知道为什么不能使用$("ul")[0]直接find

That's right; 那就对了; a jQuery object acts as an extension of an array of DOM elements. jQuery对象充当DOM元素数组的扩展。 If you access any of them by index, you get a raw DOM object, not another jQuery object. 如果按索引访问它们中的任何一个,则将得到一个原始DOM对象,而不是另一个jQuery对象。 If you want to access a jQuery object for just one of the elements the object represents, use eq : 如果您只想访问该对象表示的元素之一的jQuery对象,请使用eq

$('ul').eq(0).find('li')

You're correct -- $("ul")[0] is not a jQuery object. 您是正确的- $("ul")[0]不是jQuery对象。 It's a DOM node (an HTMLUListElement , to be precise). 这是一个DOM节点( HTMLUListElementHTMLUListElement )。

The reason that $($("ul")[0]).find("li") works is that you can construct a jQuery object from a DOM node by passing it as a parameter to the $ function. $($("ul")[0]).find("li")起作用的原因是,可以通过将DOM对象作为参数传递给$函数来从DOM节点构造jQuery对象。 $("<ul>") , for instance, will make a ul node and wrap it in a jQuery object. 例如, $("<ul>")将创建一个ul节点并将其包装在jQuery对象中。

您可以使用$("ul:eq(0)")$("ul").eq(0)

You can use like this 你可以这样使用

$("ul").index(0);

or 要么

$("ul").eq(0)


$("ul")[0] is a DOM element

您应该使用$(“ ul”)。eq(0)代替$(“ ul”)[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM