javascript .get() 的 jquery .children()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6825152/
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 .children() of .get()
提问by gavsiu
Example:
例子:
<ul>
<li>
<a></a>
</li>
<li>
<a></a>
</li>
</ul>
I can use $('ul').children('li').get(0);
to get the list item. How can I use .children('a')
to traverse down the tree?
我可以$('ul').children('li').get(0);
用来获取列表项。我怎样才能使用.children('a')
遍历树?
I tried something like $('ul').children('li').get(0).children('a');
but that does not work.
我试过类似的东西,$('ul').children('li').get(0).children('a');
但这不起作用。
For future reference:
备查:
- I will be doing other things to the
li
other than traversing down to thea
, which is why I am trying to use.children()
. - Index will be dynamic and not always 0.
- 我会做其他的事情到
li
比向下遍历到另一个a
,这就是为什么我试图使用.children()
。 - 索引将是动态的,并不总是 0。
Which is why .eq() is the preferred answer. Now I can do something like:
这就是为什么 .eq() 是首选答案。现在我可以做这样的事情:
_load = function(index) {
image_get = thumbs.children('li').eq(index);
[...]
$(function() {
var img = $(new Image());
img
.load(function() {
[...]
}
.attr('src', image_get.children('a').attr('href'));
});
}
_load(0);
^^^ WIP. Code unfinished.
^^^ WIP。代码未完成。
回答by Paul
.get()
returns a DOM Element. You can wrap it back in a jQuery object like:
.get()
返回一个 DOM 元素。您可以将其包装回一个 jQuery 对象,例如:
$($('ul').children('li').get(0)).children('a');
ButI think what you really want is .eq()
instead of .get()
:
$('ul').children('li').eq(0).children('a');
Edit
编辑
As Reid kindly pointed out in the comment below,
正如里德在下面的评论中亲切地指出的那样,
$('ul').children('li').eq(0).children('a');
$('ul').children('li').eq(0).children('a');
is semantically equivalent to the more concise :
在语义上等同于更简洁的:
$('ul > li:first-child > a');
$('ul > li:first-child > a');
which does the same as the above with a single selector.
使用单个选择器执行与上述相同的操作。
回答by jfriend00
Why not just put it all in the selector and let that do all the work for you:
为什么不把它全部放在选择器中,让它为你做所有的工作:
$('ul li:first a')
This will get a jQuery object for the first <a>
tag in your sample HTML.
这将为<a>
您的示例 HTML 中的第一个标签获取一个 jQuery 对象。
The selector logic works like this: Find all ul tags, the find the first li tag in each, then get all the a tags in each of the first li tags. The result is a jQuery selection which you can then apply various operations to.
选择器逻辑是这样工作的:查找所有 ul 标签,在每个标签中找到第一个 li 标签,然后获取每个第一个 li 标签中的所有 a 标签。结果是一个 jQuery 选择,然后您可以对其应用各种操作。
Demo here: http://jsfiddle.net/jfriend00/5qZP5/
回答by Jason Gennaro
You can do this
你可以这样做
$('ul li a:first');
$('ul li a:first');
http://jsfiddle.net/jasongennaro/yCAT6/
http://jsfiddle.net/jasonennaro/yCAT6/
$('ul li a');
returns all of the a
s in that list.
$('ul li a');
返回a
该列表中的所有s。
:first
filters for just the first.
:first
过滤器只是第一个。