Javascript 单击行后,从另一行中删除所选类

Javascript 单击行后,从另一行中删除所选类,javascript,jquery,html,Javascript,Jquery,Html,我的JQuery代码有一个小问题 我用HTML创建了一个简单的表 <table class="table"> <tr> <th>Name</th> <th>Surname</th> <th></th> </tr> <tr> <td>name 1</td> <td>surname 1</td>

我的JQuery代码有一个小问题

我用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>
我尝试从单击的
行中查找最近的表,并获取所有子项
, 下一个在循环中删除“
选定的
”类并添加到单击的
此类

但是总是
alert(rows.length)
返回我0
row
s:为什么不简单

$('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
});
写下:

$('.table tr').not(':first').on('click', function(){
 $('.table tr').removeClass('selected');
 $(this).addClass('selected');
});
根据你的问题,这样写:

var rows = $(this).siblings("tr");
而不是:

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

首先从所选类中删除类,然后将该类添加到新类中

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

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

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

是的,它是有效的,但是当我在站点上只有几个表时,它会清除所有表中的所有“选定”类,我尝试为所有表编写一个JQuery函数,但感谢您的回答现在我知道:)谢谢,它是有效的,但是当我在站点上只有几个表时,它会清除所有表中的所有“选定”类,我试着为所有表编写一个JQuery函数,但谢谢你的回答。现在,你的代码向我解释了我的错误:)谢谢,我认为,gurvinder的答案是最适合你的答案。对于另一种情况,我仍然保留我的初始答案(如果从一个表中选择了一行,则任何人都希望从任何表中取消选择。)
$('tr').not(':first').click(function () {

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

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