如何检查元素是不是第一个孩子?

Jam*_*mes 29 html jquery dom css-selectors jquery-selectors

你怎么知道当前元素是不是第一个孩子?

它应该适用于$(this),例如:

$("li").click(function(e) {
    if (/* $(this) is not the first-child */)
    {
        /* do something */
    }
});
Run Code Online (Sandbox Code Playgroud)

sli*_*kts 57

你可以这样做只是为了测试一个元素,如果它是第一个孩子:$(this).is(':first-child').其他选择器:last-child也会起作用.

  • 另外,`.not(':first-child')`仍会返回一个jQuery集,而不是一个布尔值...`.is(':not(:first-child)')`.... (12认同)
  • 那将为所有东西返回`true` ...`:first`会检查它是jQuery集中的第一项,我相信你可能想要`:first-child` (4认同)
  • 当@WorkingHard要求知道"不是"第一个孩子时,如果元素"是"第一个孩子,则该解决方案返回.没有提到基本上所有答案都是由@gnarf赠送的.我本来希望@gnarf回答这个问题,并且SO用户没有投票给错误的答案(当它完全错误时它至少有3分). (2认同)

use*_*716 30

你可以简单地询问它的.index()位置(相对于它的兄弟姐妹).

$(this).index();   // returns a zero based index position
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是,`.index()`将为第一个子项返回"0",这是假的,其他任何都是真的,因此,`.index()`实际上将为除第一个孩子之外的任何东西返回true.完美的答案 (6认同)

Ste*_*ler 10

对于所有li的在#thing不在第一个孩子:

$('#thing li:not(:first-child)')
Run Code Online (Sandbox Code Playgroud)

http://api.jquery.com/not-selector/


ped*_*and 5

另外,您可以检查是否$(this).prev().length已定义,例如:

if (!$(this).prev().length){ //This means $(this is the first child
    //do stuff
}
Run Code Online (Sandbox Code Playgroud)