我正在生成大型表格,每行都有一个复选框,类“chcktbl”。
在表格标题中,有一个全选复选框,类“chckHead”。
选择/取消选择全部功能工作正常,我在表标题中显示的所选图表的计数也是如此。
启用 Shift+单击功能以选择一系列复选框的功能也可以使用,但在当前格式下,在弹出窗口中生成错误消息之前仅选择 10 个复选框:
“停止运行此脚本?此页面上的脚本导致您的网络浏览器运行缓慢。如果它继续运行,您的计算机可能会变得无响应。”
<script type=text/javascript>
//select all button
$('#chckHead').click(function() {
if (this.checked === false) {
$('.chcktbl:checked').attr('checked', false);
}
else {
$('.chcktbl:not(:checked)').attr('checked', true);
}
countSelected();
});
//count number of boxes checked
function countSelected() {
var numCharts = $('input.chcktbl:checked').length;
$('#numCharts').html(numCharts);
}
//SHIFT+Click to select a range of checkboxes:
// this variable stores the most recently clicked checkbox
// it is used for shift-clicks
var lastClickedBox = 0;
// the checkbox functionality is default to the browser
$('.chcktbl').click(function(event) {
var clickedBox = $('.chcktbl').index(event.target);
if(event.shiftKey) {
setCheckboxes(lastClickedBox, clickedBox);
};
lastClickedBox = clickedBox;
countSelected();
});
// sets all the checkboxes between the specified indices to true
function setCheckboxes(end, start) {
if(start > end) {
var temp = start;
start = end;
end = temp;
};
for(var i = start; i < end; i++) {
$('.chcktbl').eq(i).prop('checked', true);
};
countSelected();
};
</script>
这是一个非常常见的功能,只需单击一下即可选择一系列项目,但我找不到有效的方法来做到这一点。如果有人知道更好的方法来解决这个问题,或者可以发现代码中的一些低效之处,请告诉我。
最佳答案
使用 jquery 怎么样 nextUntil ?
我实际上没有测试这个,但这应该给你基本的想法,并且它删除了 for 循环。在使用 nextUntil/prevUntil 之前,我创建了与此类似的功能,并且从未出现过无响应的页面。
function setCheckboxes(end, start) {
if(start > end) {
var temp = start;
start = end;
end = temp;
};
$('.chcktbl').eq(start).nextUntil(':eq('+(end+1)+')').add().prop('checked', true);
countSelected();
};
关于javascript - Shift + 单击可选择一系列复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281643/