【问题标题】:Prop checked checkbox for selected row(s)?支持选定行的复选框?
【发布时间】:2014-08-20 19:20:09
【问题描述】:

在我的表格上单击该行将突出显示它,并且还应选中相应的复选框。此外,如果选中了 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);
    });

【问题讨论】:

    标签: javascript jquery checkbox selected prop


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      $('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

      【讨论】:

        猜你喜欢
        • 2017-12-19
        • 1970-01-01
        • 2023-03-28
        • 2011-05-08
        • 1970-01-01
        • 2011-06-20
        • 2019-12-17
        • 2020-02-03
        • 1970-01-01
        相关资源
        最近更新 更多