选中当前复选框上方的所有复选框(如果按下 shift 键处于选中状态)

Select all the checkboxes above the current checkbox if selected with shift key pressed

本文关键字:复选框 shift 状态 于选中 如果      更新时间:2023-09-26

我在html正文中有很多复选框,有些复选框有一个特定的css类。

只是希望每当我选中一个按下 shift 键的复选框时,所有复选框仅在当前复选框上方,并且仅在之前某个事件中已经选中(选择)的复选框下方,相应的 css 类在 DOM 中选中(选择),应该自动选中(选择)。

其余所有复选框应保持不变。

这是我正在尝试做的:

.html

<input type="checkbox" class="select-row"/>
<input type="checkbox" class="select-row"/>
<input type="checkbox" />
<input type="checkbox" class="select-row"/>
<input type="checkbox" class="select-row"/>
<input type="checkbox" />
<input type="checkbox" class="select-row"/>
<input type="checkbox" class="select-row"/>
<input type="checkbox" />
<input type="checkbox" class="select-row"/>

.js:

$('.select-row').click(function(e){
if ( e && e.originalEvent.type === "click" && e.originalEvent.shiftKey === true) {
    //what to write?
  }
});

这是jsfiddlehttp://jsfiddle.net/839pS/8/

我该怎么做?

使用 .prevUntil() 函数选中前面的复选框,然后对它们执行所需的任何操作(例如将其 checked 属性设置为 true):

var $previousCheckboxes = $(this).prevUntil(':checked', 'input[type="checkbox"]');
$previousCheckboxes.prop('checked', true);

更新的 jsFiddle

我不完全确定确切的停止条件,所以我只是为了示例的目的选择了"它到达的第一个选中复选框"。在对问题的评论中讨论之后,这个jsFiddle是所需的确切功能。