如果选中复选框,则更改tr的类 [英] Change class of tr if checkbox is selected

查看:81
本文介绍了如果选中复选框,则更改tr的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中包含以下行:

I have a table that has rows like:

<tr>
    <td><input type="checkbox" /></td>
    <td><a href="#">School</a></td>
    <td><a href="#">DD1 1AB</a></td>
    <td>80.10</td>
    <td>200</td>
    <td><span class="active">Active</span></td>
    <td><a href="#">John Doe</a><br/>00000 000000</td>
</tr>

我想做的是,当用户选中复选框时,将父级<tr>的类更改为"selected",以便用户知道他们选择了哪一行.注意:他们可以打开和关闭这些功能!

What I want to do is when a user has selected the checkbox is change the the class of the parent <tr> to say selected so the user knows which row they have selected. NOTE: They can toggle these on and off!

推荐答案

假设某些复选框可能已预先选中,我会采用这种方法:

Assuming some of the checkboxed may come pre-checked, I'd take this approach:

// First add class for pre-checked entries
$(".xyz input[type=checkbox]:checked").each(function() {
    $(this).closest("tr").addClass("selected");
});

// Then toggle class whenever checkbox state changes
$(".xyz input[type=checkbox]").live("change", function() {
    $(this).closest("tr").toggleClass("selected");
});

实时演示: http://jsfiddle.net/cUxmG/

为减少两次搜索DOM的开销,可以将其合并为:

To reduce overheads of searching the DOM twice, that can be combined into:

$(".xyz input[type=checkbox]").live("change", function() {
    $(this).closest("tr").toggleClass("selected");
}).filter(":checked").each(function() {
    $(this).closest("tr").addClass("selected");
});

它执行相同的操作: http://jsfiddle.net/cUxmG/2/

这篇关于如果选中复选框,则更改tr的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆