如何检查元素是否是最后一个兄弟?
对于连续的最后一个单元格,我想执行不同的操作。
这不起作用:
$('td').each(function(){
var $this = $(this);
if ( $this === $this.parent().last('td') )
{
alert('123');
}
})
如果我删除.parent()
也不会。
尝试
$('tr td:last-child').each(function(){
var $this = $(this);
alert('123');
});
这更优雅,对我有用:
if($(this).is(':last-child'))
{
alert('123');
}
在这里,你去,但只有你想对其他tds做一些事情才有意义,其他明智的做法是使用其他答案中描述的最后一个孩子的方法。
$('td').each(function(){
var $this = $(this);
if ($this.index() == $this.siblings().length-1)
{
alert('123');
}
})
你可以这样编码。
var $this = $(this);
if($this.index()==$this.siblings().size()-1)
{
alert("It's the last.");
}
如果要选择具有公共点的不同标记的多个元素(例如:所有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
}
})