【发布时间】:2014-07-07 16:12:30
【问题描述】:
我正在使用 .each 函数来隐藏/显示表格的列。但问题是 IE 中的代码非常慢。在互联网上搜索后,我发现这可能是因为我的 .each() 函数和 $(this)。
有关我为什么使用此代码的更多信息,您可以查看此帖子:Hide/show column
这是我的旧代码: 在页面上包含 JQuery.min.js
javascript:
$(function () {
$('table th').each(function (_id, _value) {
if(_id > 2){
if($(this).find("a").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
}
else{
if($(this).find("div").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
}
}
}
});
});
HTML:
<div id="togglers">Show/Hide columns<br/></div>
我尝试使用此代码转换我的 javascript(来源:jQuery very slow in IE),但我认为我的 i(或 _id)和 _value 仍然存在问题...
$(function () {
var items = $('table th');
var $currentItem;
for (var i = 0, j = items.length; i < j; i++) {
$currentItem = $(items[i]); // in place of $(this)
function (i, _value) {
if(i > 2){
if($currentItem.find("a").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle();
e.preventDefault();
});
}
else{
if($currentItem.find("div").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle();
e.preventDefault();
});
}
}
}
}
}
});
我可能需要使用其他代码。欢迎任何建议! Tnx。
【问题讨论】:
-
速度慢的原因是你的代码一团糟。例如,当您知道只需要第四个 TH 元素及以上元素时,为什么还需要迭代?
-
你为什么要
parseInt(_id + 1)?_id和1都已经是数字了。您需要做的就是:(_id + 1)和括号只是防止变量被连接到字符串本身,而不是加在一起。 -
查看其他帖子为什么我使用此代码... (stackoverflow.com/questions/24568739/hide-show-column/24569240)
-
@endeka jQuery 增加了一些开销。但真正的问题是你使用它的方式。 :)
-
@YuryTarabanko 最后一个问题:我想“分组”不同的列,例如颜色和数字将是顶部的“更多信息”。因此,您会在顶部看到“更多信息”,如果单击它,则可以看到颜色和编号列。这可能吗?
标签: javascript jquery performance each