2010-09-28 80 views
1

父元素的事件帮助我弄清楚如何父元素(<tr>) 我找不到错误在条件上设置事件如何设置使用jQuery

<script type="text/javascript"> 
$('table tbody tr').each(function(){ 
    $(this).find('a:first').click(function(){ 
     if($(this).parents().get(1).tagName == 'TR') { 
     $(this).parents().get(1).find('tr').css('background', 'red'); //What's wrong? 
     } 
}); 
</script> 

<table> 
    <tbody> 
     <tr> 
     <td><a href="#">text</a></td> 
     <td>text</td> 
     </tr> 
    </tbody> 
</table> 

不幸的是,格式化,我看不出有什么更特殊的标记

+0

如果你使用'console.log'或'alert($(this).parents()。get(1))'',你会得到什么? – 2010-09-28 07:31:40

回答

1

嘿,你是失踪关闭});each声明。这里是你的代码

$('table tbody tr').each(function(){ 
    $(this).find('a:first').click(function(){ 

      if($(this).parents().get(1).tagName == 'TR') { 
       $($(this).parents().get(1)).css("background-color", 'red'); //What's wrong? 
      } 
     });  
}); 

Working Example

编辑的正确版本:可以缩短上面的代码很容易像分配类的锚标记。

<a class="bindclick" href="#"></a> 

$(".bindclick").bind("click", function(){ 
    var parent = $(this).parents("tr").get(0); 
      OR 
    var parent = $(this).closest("tr"); // http://api.jquery.com/closest/ 
    $(parent).css("background-color","red"); 
}); 
0

编辑:这工作:

$(function() { 
    $('tr a:first').click(function() { 
    $(this).parents('tr:first').css({background:'red'}); 
    }); 
}); 
+0

我不认为这会奏效。父母是'​​' – Marko 2010-09-28 07:38:16

+1

是的,这会起作用,问题在于,[.parents()](http://api.jquery.com/parents/)冒泡到根。意思是,如果这个表是嵌套的,那么它的所有父母TR将会受到影响。 – Reigel 2010-09-28 07:45:39

+0

+1我同意reigel。你需要在parent(“tr”)之后添加.get(0),并将其作为jQuery选择器包装,如$($(this).parents('tr')。get(0))。css ...' – 2010-09-28 07:51:23

1
$('table tbody tr').each(function(){ 
    var $this = $(this); 
    $this.find('a:first').click(function(){ 
     $this.css('background', 'red'); 
    }); 
}); 

crazy demo

1
$("table tr a:first").click(function() { 
    $(this).closest("tr").css('background', 'red'); 
}); 
+0

+1这是一个好方法。 – 2010-09-28 08:09:00

0

不能完全肯定这一点,但我认为,当你第二个函数中调用$(本)为点击标签,$(这)是一个标签本身,而不是$ (这个)在外部函数中是tr元素。

0
$('table tbody tr').each(function(){ 
      var $this = $(this); 
      $this.find('a:first').click(function(){ 
      $this.css('background', 'red'); 
     }); 
}); 
0
$('table tbody tr').each(function(){ 
    $(this).find('a:first').click(function(){ 
     $(this).css('background', 'red'); 
    }); 
}); 

容易。