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

前端 未结 5 1031
梦谈多话
梦谈多话 2020-12-05 01:29

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         


        
相关标签:
5条回答
  • 2020-12-05 02:03

    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-child method described in one of the other answers.

    $('td').each(function(){
        var $this = $(this);
        if ($this.index() == $this.siblings().length-1)
            {
                alert('123');
            }
    })
    
    0 讨论(0)
  • 2020-12-05 02:03

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

    var elements = $("*[data-foo]");
    
    elements.each(function (){
        ..
        ..your code
        ..
    
        if (elements.index(this) == elements.length - 1) {
                ..you are at the end, do something else
        }
    })
    
    0 讨论(0)
  • 2020-12-05 02:07

    This is more elegant and worked for me:

    if($(this).is(':last-child'))
    {
        alert('123');
    }
    
    0 讨论(0)
  • 2020-12-05 02:12

    Try

    $('tr td:last-child').each(function(){
        var $this = $(this);
        alert('123');
    });
    
    0 讨论(0)
  • 2020-12-05 02:19

    you can code this way.

    var $this = $(this);
    if($this.index()==$this.siblings().size()-1)
    {
       alert("It's the last.");
    }
    
    0 讨论(0)
提交回复
热议问题