【问题标题】:Finding the next input (of a parent?) with jQuery使用 jQuery 查找下一个输入(父母的?)
【发布时间】:2010-11-19 15:31:18
【问题描述】:

我在表格中有一个复选框,当你点击它时,它会相应地改变背景颜色......

$("#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>

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: javascript jquery input next


    【解决方案1】:

    您处理的事件是 tr 点击。 父母是桌子,所以这无济于事。您需要做的就是在 this 上下文中使用 find()。

    我会使用 .live 来避免使用多个事件处理程序。

    假设您在该行中只有一个复选框,然后使用以下内容。 (注意它使用 tr's inside tbody 来避免在行上运行它)

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

    【讨论】:

    • 这太好了,非常感谢 - 不过只是想了一下,无论如何要看看它是否已经检查过?
    • 是的 if ( $(this).find(":checkbox").is(':checked') )
    • 喜欢这个? (抱歉)$("table>tbody>tr").live("click", function() { if($(this).find(":checkbox").is(':checked')) { $( this).attr('checked', 'checked'); } else { $(this).removeAttr('checked'); } });
    • 老兄,我很抱歉 - 我真的希望这是我最后一次问任何问题,但无论如何也要更改行的颜色?例如... if ($checkbox.is(':checked')) {$checkbox.removeAttr('checked'); $checkbox.parent('tr').css('background-color', 'lightyellow'); } else { $checkbox.attr('checked', 'checked'); $checkbox.parent('tr').css('background-color', '#fff'); }
    • $checkbox.parent().parent().css('background-color', 'lightyellow');这行得通,但在编码方面可能很狡猾,嘿!
    【解决方案2】:

    你想改变这个:

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

    到这里:

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

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

    【讨论】:

    • 非常好,顺便说一句,感谢您的解释 - 干杯!
    【解决方案3】:

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

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

    jQuery Docs on Attributes 可能会有所帮助。


    感谢 redsquare 注意到不需要 .parent("tr")

    【讨论】:

    • 这是 tr,parents('tr') 不会匹配任何东西,除非他在我认为他不在的嵌套表中。
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 2016-05-06
    • 1970-01-01
    相关资源
    最近更新 更多