21

我使用此功能使我的表格行可点击

    $("#grid tbody tr").click(function () {
    var $checkbox = $(this).find(':checkbox');
    $checkbox.attr('checked', !$checkbox.attr('checked'));
});

它工作正常,但是当我尝试单击复选框自身时,它不起作用。我应该怎么做才能使它们都起作用?

4

5 回答 5

34

使用单个事件处理程序:

$("#grid tbody tr").click(function(e) {
    if (e.target.type == "checkbox") {

        // stop the bubbling to prevent firing the row's click event
        e.stopPropagation();
    } else {
        var $checkbox = $(this).find(':checkbox');
        $checkbox.attr('checked', !$checkbox.attr('checked'));
    }
});

http://jsfiddle.net/karim79/UX2Fv/

于 2011-04-18T10:16:33.600 回答
5
$('#grid tbody tr input:checkbox').click(function(e) {
    e.stopPropagation();
});

然后单击该复选框将不会触发 tr 上的单击事件。

于 2011-04-18T10:15:24.577 回答
3

更好的是你可以用简单的 HTML 来做到这一点,把 for属性写在label

<input type="checkbox" id="myCheck"><label for="myCheck">CheckThis</label>
                              ^                   ^

注意idof<input type="checkbox"将是for属性的值<label>

演示

于 2011-04-18T10:18:58.350 回答
0

尝试这个

$('#grid tbody tr input:checked').click(function(e) {
    e.stopPropagation();
});
于 2016-09-10T08:01:10.097 回答
0

这些答案都很好,但我被困了很长时间,试图弄清楚为什么我不能让它们工作。我正在动态生成我的表格行,但它们在 DOM 上还不存在。出于这个原因,没有一个解决方案奏效。

为我解决这个问题的是使用on()方法。

$('body').on('click', '#grid tbody  tr', function (e) {
于 2015-09-17T01:38:31.473 回答