2009-08-17 7 views
18

스크립트를 선택하여 강조 표시된 행을 강조 표시하고 행이 선택/강조 표시 될 때 다른 행이 선택/강조 표시되도록하고 싶습니다. 행이 선택됩니다. 어떻게해야합니까?Jquery : 클릭시 테이블 행 강조 표시/강조 표시

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

HTML 테이블

<table id="newCandidatesTable"> 
    <thead> 
     <tr> 
      <th style="cursor: pointer;">ID</th> 
      <th style="cursor: pointer;">Navn</th> 
      <th style="cursor: pointer;">Email</th> 
      <th></th> 
     </tr> 
    </thead> 
    <tbody> 
    <% foreach (var candidate in Model.Ansogninger) 
    { 
     %> 
      <tr id="<%= candidate.AnsogerID %>" class="newCandidatesTableTr"> 
       <td><div id="candidateID"><%= candidate.AnsogerID %></div></td> 
       <td><div id="<%= "candidateName_" + candidate.AnsogerID %>" class="candidateNameTD"><%= candidate.Navn %></div></td> 
       <td><div id="candidateEmail"><%= candidate.Email %></div></td> 
       <td> 
        <div id="<%= "acceptCandidateButton_" + candidate.AnsogerID %>" class="acceptb" style="cursor: pointer; border: 1px solid black; width: 150px; text-align: center;">Godkend</div> 
       </td> 
      </tr> 
     <% 
    } %> 
    </tbody> 
    </table> 

답변

22

먼저 모든 선택을 취소 할 수 : 여기

그것은 선택 해제,하지만 난 다시 같은 행을 클릭하면 행을 선택하는 현재 코드입니다 행과 같은

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

편집 : yep, sry,하지만 th 최고의 .live를 사용

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

이렇게하면 클릭 한 행만 선택 취소됩니다. –

+0

덕분에, 나는 당신의 아이디어를 사용했습니다 ... 그것은 나를 위해 가장 논리적이었습니다. – Poku

+1

btw 중첩 된 테이블이 있으면 모든 tr과 일치합니다. 가장 가까운 쪽이 더 낫다. – redsquare

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

이는 현재 테이블에 영향을 미칠 것이다), 전자의 생각은 옳았다. 하나의 이벤트가 많은 것보다 선호됩니다 (큰 테이블, 큰 오버 헤드를 생각하십시오).

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

:

+0

@redsquare - 그가 행을 동적으로 추가/삽입하지 않는 한 필요하지 않습니다. – karim79

+0

그는 행이 많은 경우입니다. 100 개의 이벤트보다 1 개의 이벤트 – redsquare