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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2681581/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:02:22  来源:igfitidea点击:

jQuery: how do I check if an element is the last sibling?

jquery

提问by Haroldo

How do I check if an element is the last sibling?

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

For the last cell in a row I want to perform a different action.

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

This doesn't work:

这不起作用:

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

And neither does it if I remove .parent().

如果我删除.parent().

采纳答案by rahul

Try

尝试

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

回答by bbeckford

This is more elegant and worked for me:

这更优雅,对我有用:

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

回答by ntziolis

Here you go, but that only make sense if you want to do something to the other tds as well other wise use the last-childmethod described in one of the other answers.

给你,但只有当你想对其他 tds 做一些事情时才有意义,否则明智地使用其他答案之一中描述的last-child方法。

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

回答by legendJSLC

you can code this way.

你可以这样编码。

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

回答by Caner SAYGIN

If you want to select multiple elements which are different tags with a common point, (for ex: all data-fooattribute defined tags like divs, inputs, text areas, etc.) you can follow this code:

如果要选择具有共同点的不同标签的多个元素(例如:所有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
    }
})