选中行的支票选中复选框?

时间:2014-08-20 19:20:09

标签: javascript jquery checkbox selected prop

在我的桌子上点击该行会突出显示它,还应该选中相应的复选框。此外,如果选中checkall复选框,则应突出显示所有行。如果检查删除,则应删除突出显示。我不能给id,并且想用.find()或.closest()或类似的东西动态地做这个。有任何想法吗?提前致谢! http://jsfiddle.net/7vLdxddr/3/

的jQuery

$('table').on('click', 'tr', function () {
                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                }
                else {
                    $('tr.selected').removeClass('selected');
                    $(this).addClass('selected');
                }

});

$("input[type=checkbox].checkall").on("click", function () {
        $(this).parents('.table:eq(0)').find('input:checkbox').prop('checked', this.checked);
    });

2 个答案:

答案 0 :(得分:1)

使用this的实例(指的是点击的行)和find

$(this).find(":checkbox").prop("checked", true);

http://jsfiddle.net/2wpmxdp0/1/

答案 1 :(得分:0)

使用checked属性添加和删除类。

$('table').on('click', 'tr', function () {
    var $this = $(this),
        $rowCheckbox = $this.find(":checkbox");
    // Add and remove class based on the class on the row
    // You can always use this as the event is bound to the 
    // row which is clicked. So can use the this context
    if ($this.hasClass('selected')) {
        $this.removeClass('selected');
        // Uncheck the checkbox if already selected
        $rowCheckbox.prop('checked', false);
    } else {
        $this.addClass('selected');
        $rowCheckbox.prop('checked', true);
    }
});

// No need to use the checkbox selector again
// You have already added the class to it
$(".checkall").on("click", function (e) {
    // To make sure the row event is not fired
    // due to event bubbling
    e.stopPropagation();
    var isChecked = this.checked,
        $table = $(this).parents('.table:eq(0)'),
        $rows = $table.find('tr');
    $table.find('input:checkbox').prop('checked', isChecked);
    this.checked ? $rows.addClass('selected') : $rows.removeClass('selected');
});

<强> Updated Fiddle