jQuery:如何检查元素是否是最后一个兄弟?

Har*_*ldo 51 jquery

如何检查元素是否是最后一个兄弟?

对于连续的最后一个单元格,我想执行不同的操作.

这不起作用:

$('td').each(function(){
    var $this = $(this);
    if ( $this === $this.parent().last('td') )
        {
            alert('123');
        }
})
Run Code Online (Sandbox Code Playgroud)

如果我删除它也不会.parent().

bbe*_*ord 305

这更优雅,对我有用:

if($(this).is(':last-child'))
{
    alert('123');
}
Run Code Online (Sandbox Code Playgroud)

  • @SkuraZZ 选择器之间存在细微差别;:last-child 选择作为其父元素的最后一个子元素的所有元素, :last 选择最后一个匹配的元素(参见 https://api.jquery.com/category/selectors/) (2认同)

rah*_*hul 12

尝试

$('tr td:last-child').each(function(){
    var $this = $(this);
    alert('123');
});
Run Code Online (Sandbox Code Playgroud)


ntz*_*lis 7

在这里,你去,但只有你想对其他tds做一些事情才有意义,其他明智地使用其他答案中描述的最后一个孩子的方法.

$('td').each(function(){
    var $this = $(this);
    if ($this.index() == $this.siblings().length-1)
        {
            alert('123');
        }
})
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以这样编码。

var $this = $(this);
if($this.index()==$this.siblings().size()-1)
{
   alert("It's the last.");
}
Run Code Online (Sandbox Code Playgroud)