javascript - 单击行后,从其他行中删除选定的类

标签 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>
    <td>actions</td>
</tr>
<tr>
    <td>name 2</td>
    <td>surname 3</td>
    <td>actions</td>
</tr>
</table>

然后我想突出显示 row呈黄色,当我点击此row时 所以当我点击row时添加类“selected ”,但是当我单击另一个 row 时我必须从上一行中删除“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并获取所有 child <tr> , 接下来在循环中删除“selected”类并添加到单击的row这门课。

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

请帮助我。

谢谢。

最佳答案

为什么不简单

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

关于javascript - 单击行后,从其他行中删除选定的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34837081/

相关文章:

javascript - 带参数的 PHP 函数

javascript - 这2个功能有区别吗?

javascript - 表行悬停、背景更改和单击但行中的某些子单元格具有不同的属性

javascript - 使用 JavaScript 的样式

php - 表单外的表单元素

javascript - 如何附加到 Firefox 附加组件中的文件?

javascript - 提交表单后如何检查数据库中存在的文本框值

c# - $.Ajax POST,访问返回数据

javascript - 我正在使用 Laravel 5.4 : and js not loading in blade during editing

html - 使用 CSS 隐藏背景的透明边框