【发布时间】:2011-05-02 02:59:18
【问题描述】:
在我深入研究 jQuery/Sizzle 源之前,我想我会在这里询问如何加快以下方法的速度。
这是一个标准的“全选”复选框场景。标题单元格(@ 987654321)有一个复选框,当检查时检查它的表的tbody中的所有其他复选框时,它在同一列中的@。
这行得通:
// We want to check/uncheck all columns in a table when the "select all"
// header checkbox is changed (even if the table/rows/checkboxes were
// added after page load).
(function () {
// use this dummy div so we can reattach our table later.
var dummy = $("<div style=display:none />");
// hook it all up!
body.delegate(".js_checkAll", "change", function () {
// cache selectors as much as possible...
var self = $(this),
// use closest() instead of parent() because
// the checkbox may be in a containing element(s)
cell = self.closest("th"),
// Use "cell" here to make the "closest()" call 1 iteration
// shorter. I wonder if "parent().parent()" would be faster
// (and still safe for use if "thead" is omitted)?
table = cell.closest("table"),
isChecked,
index;
// detaching speeds up the checkbox loop below.
// we have to insert the "dummy" div so we know
// where to put the table back after the loop.
table.before(dummy).detach();
index = cell.index();
isChecked = this.checked;
// I'm sure this chain is slow as molasses
table
// get only _this_ table's tbody
.children("tbody")
// get _this_ table's trs
.children()
// get _this_ table's checkboxes in the specified column
.children(":eq(" + index + ") :checkbox")
// finally...
.each(function () {
this.checked = isChecked;
});
// put the table back and detach the dummy for
// later use
dummy.before(table).detach();
});
} ());
但是,对于 250 多行,它开始变慢(至少在我的机器上)。用户可能需要多达 500 行数据,因此分页数据不是解决方案(项目已分页 @ 500/页)。
任何想法如何加快速度?
【问题讨论】:
-
也许您可以为所有复选框指定一个类,或者您可以尝试停止使用 jQuery,因为在某些情况下它可能比自定义代码慢
-
我会尝试删除一些 jquery 选择器。
-
你可以使用 JS 模板引擎来处理大列表,它比 DOM 更快
标签: javascript jquery performance css-selectors