我有一个HTML表,其中包含大约1000行和26列。我正在使用this jQuery plugin在行之间导航并进行选择。
我的第一个问题是该插件工作正常,但即使使用最新版本(0.6.1) - 使用1000行时速度非常慢。
我的第二个问题是我想创建一个表示表中所选行的JSON对象。我写了一个这样做的功能,但是在这么大的桌子上它又太慢了。以下代码有效,但我想优化它:
$(document).bind("keyup", function(event) {
var jsonText = "";
var i = 0;
var td_size = $("tr.selected td").size();
jsonText += "{";
for (i = 0; i < td_size; i++) {
if (i < td_size - 1) {
if (i == 0) {
// Get link URL.
jsonText += "\"" + $("thead tr th").eq(i).text() + "\":\"" + $("tr.selected td").eq(i).find("a").attr("href") + "\",";
} else {
jsonText += "\"" + $("thead tr th").eq(i).text() + "\":\"" + $("tr.selected td").eq(i).text() + "\",";
}
}
else {
jsonText += "\"" + $("thead tr th").eq(i).text() + "\":\"" + $("tr.selected td").eq(i).text() + "\"";
}
}
jsonText += "}";
$('#content').html('').append(jsonText);
});
有什么建议吗?
答案 0 :(得分:1)
您可以做的一件事是优化您的jQuery选择器,以帮助Sizzler更快地工作...... 而不是绑定所有文件的密钥,特定tr的密钥怎么样?
$("tr.selected td").size(); // slow
$("table").find(".selected").find("td"); // probably faster
将选定的tr保存在循环外,你要求sizzler通过循环1000行找到你的对象26次!
$("thead tr th").eq(i) // on every loop element? slow, try saving the information before the keyup event, they are not going anywhere are they?
所以这样的事情可能会更快:
var $allTrs = $("tr");
var $allHeads = $("thead tr th");
$allTrs.bind("keyup", function(event) {
var jsonText = "";
var i = 0;
var $t = $(this),
$alltds = $t.find("td"),
td_size = $alltds.length();
jsonText += "{";
$.each($alltds, function(i){
jsonText += "\"" + $allHeads.eq(i).text() + "\":\"";
if (i == 0){ // you have a strange condition, will leave it up to u
// append link
jsonText += $(this).find("a").attr("href"); // i remove "" for better readability
}else{
// append text
jsonText += $(this).text();
}
});
jsonText += "}";
$('#content').text(jsonText); // cheaper than html
});
我还没有测试过。
你也可以直接创建一个json对象(不会影响它的速度),比如这个
var mynewjson = {};
然后在循环中:
mynewjson[name] = value;