2016-01-17 19 views
1

我有一個小問題,我的JQuery代碼。點擊行後,從其他行中刪除seletced類

我在HTML中創建了簡單的表格。

<table class="table"> 
<tr> 
    <th>Name</th> 
    <th>Surname</th> 
    <th></th> 
</tr> 
<tr> 
    <td>name 1</td> 
    <td>surname 1</td> 
    <td>actions</td> 
</tr> 
<tr> 
    <td>name 2</td> 
    <td>surname 3</td> 
    <td>actions</td> 
</tr> 
</table> 

然後我想強調的黃色row,當我點擊這個row 所以,當我點擊row添加類「selected」但是當我點擊另一個row我不得不刪除「selected」上一行的類。於是,我就在環刪除「selected」類中創建JQuery的行動

$('tr').not(':first').click(function() { 
    var table = $(this).closest("table"); 
    var rows = table.children("tr"); 
    alert(rows.length); 
    rows.each(function() { 
     $(this).removeClass("selected"); 
    }); 

    $(this).addClass('selected'); 
}); 

我試圖找到最接近的表從這個點擊row,並得到所有的孩子<tr>, 旁邊並添加點擊row這個類。

但總是alert(rows.length)返回我0 row S:<

請幫助我。

謝謝。

回答

1

何不乾脆

$('tr').not(':first').click(function() { 
    $(this).addClass("selected"); //add class selected to current clicked row 
    $(this).siblings().removeClass("selected"); //remove class selected from rest of the rows 
}); 
+0

謝謝,它在現場爲少數表工作! –

0

這樣寫:

$('.table tr').not(':first').on('click', function(){ 
$('.table tr').removeClass('selected'); 
$(this).addClass('selected'); 
}); 

根據您的問題,這樣寫:

var rows = $(this).siblings("tr"); 

相反的:

var rows = table.siblings("tr"); 
+0

是的,它的工作,但是當我在網站上有幾個表清除所有表中的所有「選定」類,我試圖爲所有表寫入一個JQuery函數 但謝謝回答 –

+0

在代碼中做上述更改。 –

+0

現在我知道:) 感謝 –

0

首先從選定的類中刪除類,然後將類添加到新的類中。

$('tr').not(':first').click(function() { 

    $('tr.selected').removeClass("selected"); 

    $(this).addClass('selected'); 
}); 
+0

是的,它的工作原理,但是當我在網站上有幾張表,它清除所有表中的所有「選定」類,我試圖爲所有表寫一個JQuery函數但謝謝回答 –

+0

對, 現在你的代碼向我解釋我的錯誤:) 謝謝 –

+0

我認爲,gurvinder的答案是最適合你的情況。對於其他情況,我仍然保留我的初始答案(如果任何人想從任何表中取消選擇,如果選擇了一個表中的一行)。 –