Jquery:单击突出显示/取消突出显示表行

我希望我的脚本突出显示我选择的行并且效果很好,但是当选择/突出显示行时,如果选择了另一行,我希望它“取消选择/取消选择”。 我该怎么做呢?

这是用于选择行的当前代码,它取消选择,但仅当我再次单击同一行时:

$(".candidateNameTD").click(function() { $(this).parents("tr").toggleClass("diffColor", this.clicked); }); 

Html表

   <tr id="" class="newCandidatesTableTr"> 
ID Navn Email
<div id="" class="candidateNameTD">
<div id="" class="acceptb" style="cursor: pointer; border: 1px solid black; width: 150px; text-align: center;">Godkend

您可以先取消选择所有行,例如

  $(".candidateNameTD").click(function() { $(this).closest("tr").siblings().removeClass("diffColor"); $(this).parents("tr").toggleClass("diffColor", this.clicked); }); 

编辑:是的,sry,但想法是对的;)

 $(".candidateNameTD").click(function() { $("tr").removeClass("diffColor"); $(this).parents("tr").addClass("diffColor"); }); 

这只会影响当前表:

 $(".candidateNameTD").click(function() { $('table#newCandidatesTable tr').removeClass("diffColor"); $(this).parents("tr").addClass("diffColor"); }); 

最好使用.live 。 一个事件比许多事件更受欢迎(想想大表,大开销)。

 $("div.candidateNameTD").live('click'. function() { var $tr = $(this).closest("tr"); //remove any selected siblings $tr.siblings().removeClass('diffColor'); //toggle current row $tr.toggleClass('diffColor'); });