如何在单击时更改表格行的颜色,并在单击另一行时更改回原来的颜色

How to change a table row color when clicked and back to what it was originally when another row clicked?

本文关键字:颜色 单击 原来 一行 表格      更新时间:2023-09-26

正如标题所解释的,我希望在单击一行时更改该行的颜色,然后在单击另一行时恢复该颜色,但仍然更改新单击的行的颜色。

JQuery中的解决方案将不胜感激。我就是打不破这个。到目前为止我所拥有的,但对我不起作用。

function loadjob(jobIDincoming, currentID){
$("#joblistingDetail").load('jobview.php' , {jobID: jobIDincoming}).hide().fadeIn('100');
var last = new Array();
last.push(currentID);
$(last[last.length-1]).closest('tr').css('background-color', 'white');
$(currentID).closest('tr').css('background-color', 'red');};

无需将事情复杂化。这是尽可能简单的。

$("table tr").click(function() {
   $("table tr").css("background", "#fff"); //reset to original color
   $(this).css("background", "#fo0"); //apply the new color
});

您尚未显示marup,因此

$(document).delegate("tr","click",function(e){
  $("tr").css('background-color', 'white');
  $(this).css('background-color', 'red');
});

DEMO

我会使用

$(document).on('click', 'tr', function(e){
    // reset rows
    $('tr').css('background-color', 'white');
    // set colour of row raising the click event 
    $(this).css('background-color', 'red');
});

我也会用$.on作为它的酷。。。读一读为什么会这样!

你可以使用一个类,比如:

.selected td { background-color: #CCC; }

然后在使用.delegate()单击时应用它,如下所示:

$("#tab1").delegate("tr", "click", function() {
   $(this).addClass("selected").siblings().removeClass("selected");
});

http://jsfiddle.net/nick_craver/Ymd65/