改变tr背景颜色

use*_*625 17 css jquery

我有这样的事情:

<tr id='<%=currentRow %>' onclick="SetBackgroundColor(this)" style="background-color:Yellow">
Run Code Online (Sandbox Code Playgroud)

当我点击一行我想改变它的背景颜色,我喜欢这样:

function SetBackgroundColor(rowId) 
{
     $(rowId).css("background-color", "#000000");
}
Run Code Online (Sandbox Code Playgroud)

但我不知道为什么它不起作用.有什么建议吗?

Dav*_*ing 34

IE有TR元素的背景颜色问题.更安全的方法是在TR中设置TD和TH的背景:

<table id="tabletest">
    <tr>
        <td>testcell</td>
    </tr>
</table>

<script>
$('#tabletest tr').bind('click', function(e) {
    $(e.currentTarget).children('td, th').css('background-color','#000');
})
</script>
Run Code Online (Sandbox Code Playgroud)

补充:您可以为整个表分配单个事件处理程序以提高性能:

$('#tabletest').bind('click', function(e) {
    $(e.target).closest('tr').children('td,th').css('background-color','#000');
});
Run Code Online (Sandbox Code Playgroud)


Vin*_*nie 9

在jQuery中,您不必使用onclick属性来分配事件处理程序.假设您为要影响的每个tr添加一个名为mytr的类.然后你可以做这样的事情:

 $(document).ready(function(){
        $(".mytr").click(function(){
             $(this).css("background-color", "#000000");
        });
 });
Run Code Online (Sandbox Code Playgroud)

这将把事件处理程序应用于具有类mytr的所有行.


luc*_*ind 6

这将在点击新行时重置每一行......

$(document).ready(function(){

  $('tr').click(function(){
    $('tr td').css({ 'background-color' : 'green'});
    $('td', this).css({ 'background-color' : 'red' });
  }); 

});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsbin.com/aciqi/