![](/img/trans.png)
[英]What is the most efficient/fastest way to use a jQuery selector multiple times?
[英]What's the fastest, most efficient way to toggle > 10000 checkboxes with Javascript/jQuery?
我有一个包含超过 10000 个复选框的div
。
现在,将它作为技术限制,我有 10000 个复选框。 它不能也不会改变。 这不是作业。
<div class="well well-sm" style="min-height: 100px; max-height: 360px; overflow: auto; background-color: #f7f7f7;">
<label>
<input type="checkbox" class="checkbox-item" name="some_name" value="28" checked="checked"> Item 1
</label><br />
<!-- another 10000 of these -->
</div>
这个 jQuery 代码在按下特定按钮时激活。
$('.select-all').click(function () {
$(this).parent().find(':checkbox:visible').prop('checked', true).change();
});
$('.unselect-all').click(function () {
$(this).parent().find(':checkbox:visible').prop('checked', false).change();
});
$('.select-inverse').click(function () {
$(this).parent().find(':checkbox:visible').click();
});
(忽略:visible
部分,因为列表可以被过滤)
当复选框的数量达到数千时,整个过程变得太慢,尤其是当需要切换约 10000 个复选框时。
我想知道是否有更快(不一定更好)的方式同时切换所有这些(主要用于全选/取消全选,因为反向选择可以完全删除)
好吧,我知道你有多喜欢我的 10000 个复选框,所以自从我最近搬到 50000 个复选框后,我认为发布一个答案会很有趣(也许我会得到足够多的反对票来让我继续实现 100000 个复选框的最终目标单页)。
自上次以来,我将 HTML 更新为:
<div class="well well-sm top" data-textarea-target="name-of-target">
<div class="checkbox-item">
<input type="checkbox" name="some_name" id="28" value="28" checked="checked">
<label for="28">
<span class="well-text-style-1">Item 1</span>
<span class="well-text-style-2">subtitle</span>
</label>
</div>
<!-- another 50000 of these -->
</div>
这是现在可以在 2-4 秒内操作 50000 个复选框的按钮的代码:
$('.select-all').click(function () {
// we check all visible checkboxes
$(this).parent().find(':checkbox:visible').prop('checked', true);
// other code here that calls functions to handle the removal of .change()
});
$('.unselect-all').click(function () {
// we uncheck all visible checkboxes
$(this).parent().find(':checkbox:visible').prop('checked', false);
// other code here that calls functions to handle the removal of .change()
});
$('.select-inverse').click(function () {
// we uncheck the visible, checked ones and check the visible, unchecked ones
$(this).parent().find(':checkbox:visible').prop( "checked", function( i, val ) {
return !val;
});
// other code here that calls functions to handle the removal of .click()
});
唯一发生变化的是我们删除了 the.change() 并添加了在操作完所有复选框后复制其功能的代码。
这导致能够在短短 1-2 秒和平均 3-4 秒内选中/取消选中 50000 个复选框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.