0

在我的表格上单击该行将突出显示它,并且还应选中相应的复选框。此外,如果选中了 checkall 复选框,则应突出显示所有行。如果取消检查,则应删除突出显示。我不能给出 ids 并且想用 .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);
    });
4

2 回答 2

1

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

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

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

于 2014-08-20T19:24:39.520 回答
0

使用选中的属性添加和删除类。

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

更新小提琴

于 2014-08-20T19:25:15.450 回答