使用Shift键(例如gmail)在复选框之间取消选中

时间:2017-06-13 00:08:29

标签: jquery html

使用以下代码我尝试实现像shift键功能一样的gmail。

var lastChecked = null;

$(document).ready(function() {
  var $chkboxes = $('.chkbox');
  $chkboxes.click(function(e) {
    if (!lastChecked) {
      lastChecked = this;
      return;
    }

    if (e.shiftKey) {
      var start = $chkboxes.index(this);
      var end = $chkboxes.index(lastChecked);

      $chkboxes.slice(Math.min(start, end), Math.max(start, end) + 1).prop('checked', lastChecked.checked);

    }

    lastChecked = this;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="id_chk1" class="chkbox" value="1" />Check 1<br/>
<input type="checkbox" id="id_chk2" class="chkbox" value="2" />Check 2<br/>
<input type="checkbox" id="id_chk3" class="chkbox" value="3" />Check 3<br/>
<input type="checkbox" id="id_chk4" class="chkbox" value="4" />Check 4<br/>
<input type="checkbox" id="id_chk5" class="chkbox" value="5" />Check 5<br/>

但问题是,如果我选中所有复选框并使用Shift键,如果我取消选中第3个复选框,那么它不会取消选中第4个&amp;第5位。这适用于gmail。除此之外还有其他选择吗?

1 个答案:

答案 0 :(得分:1)

设置this.checked属性时,请使用lastChecked.checked代替checked。因此,如果您使用shift键取消选中一个框,它将取消选中所有其他框,而不是复制上一个复选框的checked属性。

var lastChecked = null;

$(document).ready(function() {
  var $chkboxes = $('.chkbox');
  $chkboxes.click(function(e) {
    if (!lastChecked) {
      lastChecked = this;
      return;
    }

    if (e.shiftKey) {
      var start = $chkboxes.index(this);
      var end = $chkboxes.index(lastChecked);

      $chkboxes.slice(Math.min(start, end), Math.max(start, end) + 1).prop('checked', this.checked);

    }

    lastChecked = this;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="id_chk1" class="chkbox" value="1" />Check 1<br/>
<input type="checkbox" id="id_chk2" class="chkbox" value="2" />Check 2<br/>
<input type="checkbox" id="id_chk3" class="chkbox" value="3" />Check 3<br/>
<input type="checkbox" id="id_chk4" class="chkbox" value="4" />Check 4<br/>
<input type="checkbox" id="id_chk5" class="chkbox" value="5" />Check 5<br/>