[英]Change colour of table row onclick
我已經創建了一個具有交替顏色(例如黃色和紅色)的行的表。 現在,我想將單擊行的顏色更改為一種常用顏色(比如藍色)。再次單擊時,還原為原始顏色。 我可以使用此代碼更改顏色
$("#mainTable").find('#'+IDClicked).css("background-color", "#bbbbff");
我無法弄清楚如何恢復。
我們假設你的代碼是這樣的:
<table id="rowClick">
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
$(document).ready(function(){
$("#rowClick > tr").click(function(){
$(this).toggleClass("active");
});
});
table tr.active {background: #ccc;}
請嘗試以下代碼
CSS
.high-light{background:blue !important;}
jQuery的
$(document).ready(function(){
$('table tr').click(function(){ $(this).addClass("high-light"); });
//If you have TD's background set try the below commented code
$('table tr td').click(function(){ $(this).parent().find('td').addClass("high-light"); });
});
完全回答你的問題:
$('#box').on('click', function() {
var box$ = $(this),
isBgColorChanged = box$.data('isBgColorChanged'),
bgColor = !!isBgColorChanged ? '#444' : '#ccc';
box$.css('background-color', bgColor)
.data('isBgColorChanged', !isBgColorChanged);
});
更優雅的解決方案
$('#box').on('click', function() {
$(this).toggleClass('activated');
});
試試這個演示 :
$('table tr').toggle(function(){
$(this).addClass('myclass');
}, function(){
$(this).removeClass('myclass');
});
CSS
.myclass{
background: red;
}
table tr{
background: yellow;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.