我在表格中有一个复选框,当你点击它时,它会相应地改变背景颜色,就像这样......
$("#table tr td :checkbox").bind("click change", function() {
$this = $(this); // cache the jquery object
if($this.is(':checked')) { $this.closest('tr').css('background-color', 'lightyellow'); }
else { $this.closest('tr').css('background-color', '#fff'); }
});
效果很好,但是,我想我想做得更好,所以在您单击表格行的任意位置时,它会选中该框并突出显示该行。
我试过使用这段代码,但不幸的是它不起作用:
$("table tr").bind("click", function() {
$(this).parents("tr").find(":checkbox").attr('checked');
});
这是 HTML 代码(删除了过多的内容以提高可读性...
<td>Name</td>
<td>Description</td>
<td><input type="checkbox"></td>
非常感谢任何帮助,谢谢!
最佳答案
您处理的事件是 tr click。 parent 是 table ,所以这无济于事。您需要做的就是从 this 上下文中使用 find()。
我会使用 .live 来避免使用多个事件处理程序。
假设您在一行中只有一个复选框,那么请使用以下内容。 (注意它在 tbody 内部使用 tr 以避免在 thead 行上运行它)
$("table>tbody>tr").live("click", function() {
$(this).find(":checkbox").attr('checked', 'checked');
});
更新
如果你想切换它试试类似的东西
$("table>tbody>tr").live("click", function(ev) {
var $checkbox = $(this).find(":checkbox");
//check to see we have not just clicked the actual checkbox
if ( !$(ev.target).is(':checkbox') ){
$checkbox.is(':checked') ? $checkbox.removeAttr('checked')
: $checkbox.attr('checked', 'checked')
}
});
关于javascript - 使用 jQuery 查找下一个输入( parent 的?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1277700/