2010-06-20 67 views
1

当用户按下按钮时,需要更改包含单选按钮的div的bg颜色。我正在使用jquery - 所以它似乎应该有一些简单的方法来实现这一点。我有我的HTML设置是这样的:选择收音机btn时更改bg颜色

<div class="sales_box"> 
<table> 
<tr> 
<td class="radio_cell"><input type="radio"></td> 
</tr> 
</table> 
</div> 

<div class="sales_box"> 
<table> 
<tr> 
<td class="radio_cell"><input type="radio"></td> 
</tr> 
</table> 
</div> 

回答

6

刚刚处理的单选按钮的变化事件,然后使用jQuery的closest()方法:

$(document).ready(function(){ 
    $('input:radio').change(function(){ 
     $(this).closest('div').css('background-color', 'red'); 
    }); 
}); 

而且作为redsquare说,你不应该”真的设置内联的CSS。您应该使用toggleclass函数。我只是用css函数作为例子。

+0

这将改变TD背景 – redsquare 2010-06-20 09:20:26

+0

@redsquare - 无需downvote,给我改变,先改正它。 – GenericTypeTea 2010-06-20 09:22:06

+0

我没有-1它 – redsquare 2010-06-20 09:22:30

0

尝试

$(function() { 
     $(".radio_cell input[type=radio]").bind("click", function() { 
      $(this).parents('div:first').css("background-color", "Blue"); 
     }); 
    }); 
+1

最接近在这里,这种方式得到所有的父母然后过滤器 – redsquare 2010-06-20 09:27:40

0

我会用toggleClass而不是设置内联CSS。

$(document).ready(function(){ 
    $('input:radio').change(function(){ 
     $(this).closest('div').toggleClass('highlight'); 
    }); 
}); 
+0

我刚刚添加了一个关于取消选择行为的后续行动: http://stackoverflow.com/questions/3078781/change-bg-on-radio-deselect – Thomas 2010-06-20 09:43:29