使用 jquery 选择第一个孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4891579/
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
select first child with jquery
提问by mysterious
I am trying to select first child of ul and then remove it and then append it in the end of that ul but unfortunately i can not selet first child.
我正在尝试选择 ul 的第一个孩子,然后将其删除,然后将其附加到该 ul 的末尾,但不幸的是我无法选择第一个孩子。
Here is code
这是代码
current = 0;
$(document).ready(function(){
width=951;
var totalSlides=$(".slider ul li").length;
$(".slider ul").removeAttr('width');
$(".slider ul").attr('width',width*totalSlides);
$('#next img').click(function(){
current -= width;
$(".slider ul").animate({"left":current+"px"}, "slow");
$(".slider ul").append($(".slider ul:first-child"));
//$('.slider ul:firstChild').remove();
});
});
回答by jAndy
You don't need to .remove()helpor .detach()helpa node to append it somewhere else. You can do it by just invoking .append()helpor .appendTo()helprespectively .after()helpand .insertAfterhelp. For instance:
您不需要.remove()帮助或.detach()帮助节点将其附加到其他地方。您可以通过分别调用.append()help或.appendTo()help 来完成.after()help和.insertAfterhelp。例如:
$('ul li:first').insertAfter('ul li:last');
回答by David says reinstate Monica
The first child of the ulcan be selected:
ul可以选择第一个孩子:
$('ul > :first-child');
or:
或者:
$('ul').children().eq(0);
or:
或者:
$('ul li:first');
There are, probably, many other ways though.
不过,可能还有许多其他方式。
回答by zzzzBov
Any of these will work:
这些中的任何一个都可以工作:
$('ul > li:first')$('ul > li:first-child')$('ul > li:eq(0)')$('ul > li:nth-child(1)')$('ul > li').eq(0)$('ul > li').first()$('ul > li')[0]
$('ul > li:first')$('ul > li:first-child')$('ul > li:eq(0)')$('ul > li:nth-child(1)')$('ul > li').eq(0)$('ul > li').first()$('ul > li')[0]
回答by FlipFloop
first, make a class for every first span, like so:
首先,为每个第一个跨度创建一个类,如下所示:
<li><span class = "the_span">a1</span><span>b1</<span></li>
<li><span class = "the_span">a2</span><span>b2</<span></li>
<li><span class = "the_span">a3</span><span>b3</span></li>`
The in the Javascript, you write:
在 Javascript 中,你写:
var spanEl = document.getElementsByClassName("the_span");
There you go!
你去吧!
回答by Sjoerd
ul:first-childdoes not select the first child of ul, it selects the ul which is the first child itself. Use li:first-child.
ul:first-child不选择 的第一个孩子ul,它选择第一个孩子本身的 ul 。使用li:first-child.

