2009-11-30 72 views
15

我有這樣的事情:更改TR背景色

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

當我點擊一排我想改變它的背景色,我不喜歡這樣的:

function SetBackgroundColor(rowId) 
{ 
    $(rowId).css("background-color", "#000000"); 
} 

但我不不知道爲什麼它不起作用。有什麼建議嗎?

+0

做任何事情發生嗎?嘗試使用Firebug或一些「警告」行來縮小,如果點擊事件甚至發射,傳遞給函數等等。 – 2009-11-30 17:35:38

+0

您也可以創建一個CSS類,並將該類應用到您的TR與JavaScript。 – Roch 2009-11-30 17:37:47

+0

查看連續點擊演示http://jsbin.com/ufihi3 – Pool 2009-11-30 17:38:51

回答

30

IE具有背景顏色TR元件的問題。一個更安全的方法是設定背景爲TD的和TH的的TR內:

<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> 

新增:您可以分配一個單獨的事件處理程序,整個表,以提高性能:

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

在jQuery中,您不必使用onclick屬性來分配事件處理程序。假設你爲每個想要影響的tr添加一個名爲mytr的類。然後你可以做這樣的事情:

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

而且這將適用於類mytr的所有行的事件處理程序。

+0

什麼也沒有發生..我用螢火蟲看..它跳到哪裏它有...但沒有什麼..仍然黃色排 – user158625 2009-11-30 18:05:48

+0

你是否修改這個,所以它使用正確的選擇器? – Kezzer 2009-12-01 08:22:25

0

而不是更改表格行背景顏色,請嘗試更改表格單元格背景顏色。

$(document).ready(function() { 
    $(".mytr td").click(function() { 
     $(this).css("background-color", "#000000"); 
    }); 
}); 
1

一個更簡單的解決方案是可能對錶或addClass中的所有行使用選擇器。

$("#myTable tr").click(function() { 
    $(this).css('background-color', '#f00'); 
}); 

$("#myTable tr").click(function() { 
    $(this).addClass('selected'); 
}); 
6

這將當點擊一個新的重置每行...

$(document).ready(function(){ 

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

}); 

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

0

謝謝all..the的問題是,在母版我是裝的第j query-1.3.2.min.jsbeforequery-1.3.2-vsdoc.js,這就是方式,它不是working..thanks再次

+0

請選擇一個答案,以便我們知道你有一個解決方案。 – Mottie 2009-12-01 04:03:27

2
$('#RowID').children('td, th').css('background-color','yellow');