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

问题描述 投票:51回答:5

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

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

这不起作用:

$('td').each(function(){
    var $this = $(this);
    if ( $this === $this.parent().last('td') )
        {
            alert('123');
        }
})

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

jquery
5个回答
12
投票

尝试

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

302
投票

这更优雅,对我有用:

if($(this).is(':last-child'))
{
    alert('123');
}

7
投票

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

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

4
投票

你可以这样编码。

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

0
投票

如果要选择具有公共点的不同标记的多个元素(例如:所有data-foo属性定义的标记,如div,输入,文本区域等),您可以遵循以下代码:

var elements = $("*[data-foo]");

elements.each(function (){
    ..
    ..your code
    ..

    if (elements.index(this) == elements.length - 1) {
            ..you are at the end, do something else
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.