2010-04-21 118 views
49

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

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

这不起作用:

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

而且也不如果我删除.parent()

+5

这是行不通的原因是因为你正在比较两个jQuery对象。只有对象完全相同,对象才是平等的。 '$(this)== $(this)'是错误的..疯狂的东西。如果你做了if($ this.get(0)=== $ this.parent()。last('td')。get(0))',那么你的例子就可以工作,因为它比较了实际的DOM元素。 (http://api.jquery.com/get) – Matt 2010-04-21 09:27:31

回答

12

尝试

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

在这里,你走了,但如果你想要做的事其他TDS以及其他明智的使用在其他的答案中的一个描述的最后孩子方法才有意义。

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

这是更优雅,为我工作:

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

不错,这应该被标记为这个问题的正确答案。 – 2012-03-19 03:48:39

+2

这是我用过的。非常感谢。 – James 2012-03-24 15:47:18

+3

我希望Stack让我们投票选出一个不同的答案作为接受的答案! – Alexandru 2016-02-24 19:41:14

2

你可以用这种方式进行编码。

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