jQuery 如何检查元素是否不是第一个孩子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3676454/
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
How to check if the element is not the first-child?
提问by James
How do you know if the current element is not the first-child?
你怎么知道当前元素是否不是第一个孩子?
It should work with $(this)
, for example:
它应该与$(this)
,例如:
$("li").click(function(e) {
if (/* $(this) is not the first-child */)
{
/* do something */
}
});
回答by slikts
You can do this just to test an element if it's the first child: $(this).is(':first-child')
. Other selectors like :last-child
would work too.
你可以这样做只是为了测试一个元素,如果它是第一个孩子:$(this).is(':first-child')
。其他类似的选择器:last-child
也可以。
回答by user113716
You could simply ask for its .index()
position (relative to its siblings).
你可以简单地询问它的.index()
位置(相对于它的兄弟姐妹)。
$(this).index(); // returns a zero based index position
回答by Stephan Muller
For all li
's in #thing
that aren't first child:
因为所有li
的#thing
都不是第一个孩子:
$('#thing li:not(:first-child)')
回答by jwueller
If you would like to select everything except the first child, this is how to do it:
如果您想选择除第一个孩子之外的所有内容,请执行以下操作:
$('#some-parent').children().not(':first')
回答by pederOverland
Also, you can check if $(this).prev().length
is defined, like in:
此外,您可以检查是否$(this).prev().length
已定义,例如:
if (!$(this).prev().length){ //This means $(this is the first child
//do stuff
}
回答by BrunoLM
Check the index
检查索引
$(this).index() == 0 // is first
回答by John Doherty
Keep it simple, use the DOM
保持简单,使用 DOM
$("li").click(function(e) {
if (this.previousSibling != null)
{
/* do something */
}
});
回答by legendJSLC
$("li").click(function(e) {
if ($(this).index != 0 )
{
/* do something */
}
});