使用jQuery查找(父级的)下一个输入

3
我在表格中放了一个复选框,当你点击它时,它会相应地改变背景颜色,就像这样...
$("#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>

任何帮助都将不胜感激,谢谢!
3个回答

2
您想要更改这个内容:
$(this).parents("tr").find(":checkbox").attr('checked');

转换为:

$(this).parents("tr").find(":checkbox").attr('checked', 'checked');

否则,你所做的只是读取checked属性,而不是设置它。

非常好地发现了,顺便感谢你的解释 - 谢谢啊! - Nick

2

您正在处理的事件是tr click。父元素是table,因此这将无法帮助。您需要做的就是使用来自此上下文的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')
        }
 });

太好了,非常感谢 - 只是我有一个想法,有没有办法找出它是否已经被检查过? - Nick
是的,如果($(this).find(“:checkbox”).is(':checked')) - redsquare
这样写?(抱歉)$("table>tbody>tr").live("click", function() { if($(this).find(":checkbox").is(':checked')) { $(this).attr('checked', 'checked'); } else { $(this).removeAttr('checked'); } }); - Nick
伙计,非常抱歉 - 我希望这是最后一次向您提问,但有没有办法也改变行的颜色?例如...if ($checkbox.is(':checked')){$ checkbox.removeAttr('checked'); $checkbox.parent('tr')。css('background-color','lightyellow');} 否则{ $checkbox.attr('checked','checked'); $checkbox.parent('tr')。css('background-color','#fff' );} - Nick
$checkbox.parent().parent().css('background-color', 'lightyellow'); 这段代码可以运行,但从编码角度来看可能有点不太好,呵呵! - Nick
再次感谢你,顺便说一句,Red,你真是个超级棒的人!干杯 - Nick

1

我认为你只是忘记设置属性的值了。

$("table tr").bind("click", function() {
    $(this).find(":checkbox").attr('checked', 'checked');
});

这里有一些关于jQuery属性文档的信息,或许能对你有所帮助。


感谢redsquare发现不必要使用.parent("tr")

这是一个<tr>,parents('tr')不会匹配任何内容,除非它在嵌套表格中,而我认为它不是。 - redsquare

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接