如何使用jquery在表中选择一行?

Pra*_*ant 3 jquery select html-table

我在我的应用程序中创建了一个表,我想在单击复选框时选择(更改背景颜色)整行,与gmail一样,当我们单击gmail中的复选框时,整行变为黄色.

<table>
<tbody>
<tr>
<td><input type="checkbox" name="chk" id="chk" /></td>
<td>My Name</td>
<td>Description of the job</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

请告诉我如何在jquery中做同样的事情?

cle*_*tus 7

$(function() {
  $("#chk").click(function() {
    $(this).parents("tr").toggleClass("diffColor");
  });
});
Run Code Online (Sandbox Code Playgroud)

创建一个CSS类(上面称为"diffColor")并添加背景颜色,如:

<style type="text/css">
tr.diffColor td { background-color: yellow; }
</style>
Run Code Online (Sandbox Code Playgroud)

不要直接设置CSS属性.尽可能使用课程.


nic*_*ckf 5

Cletus的答案是正确的,但我认为可以稍微改进一下:

$(function() {
    $("#chk").click(function() {
        $(this)
            .parents("tr:first")
            .toggleClass("diffColor", this.checked)
        ;
    });
});
Run Code Online (Sandbox Code Playgroud)

这里唯一真正的区别是:

  1. 它只选择第一个父母<tr>....你永远不会知道你的代码可能会在哪里结束,而且理论上它会更快一些.
  2. 它会检查复选框的新值,并根据需要添加或删除该类.如果你知道我的意思,不检查这个,其他一些代码可能会改变行上的"diffColour"类,然后你的复选框会被反转.

此外,您可以考虑将该函数绑定到change处理程序:

$('#chk').bind('click change', function() { // ... etc
Run Code Online (Sandbox Code Playgroud)