我有一个jquery函数,它将标记添加到表的第一行。 我尝试使用append,但是它不起作用,所以我得到了一个非常慢的解决方案,它以某种方式给出错误"此页面上的脚本导致Internet Explorer运行缓慢..."
功能为
jQuery.fn.fixGridView = function () {
"use strict";
// var start = +new Date(); // log start timestamp
if (jQuery(this).is('table') && this.find('thead').length === 0) {
var theadv = "<thead><tr>" + this.find('tbody tr:first').html(); +"</tr></thead>";
this.find('tbody tr:first').remove();
var htmlv = this.html();
this.html(theadv + htmlv);
}
//var end = +new Date(); // log end timestamp
// var diff = end - start;
// alert(diff);
return this;
};
有人可以帮助我让这段代码运行得更快吗?
编辑:我必须使用IE ..这是要求(ie8)。 Edit2:我创建了js小提琴:http://jsfiddle.net/4xLzL/答案 0 :(得分:2)
要提高渲染性能,您必须了解DOM操作(包括回流和重绘)是昂贵的操作。您的代码目前重新创建了整个表格,并添加了<thead>
大部分<tbody>
内容保持不变。这个庞大的&#34;重绘&#34;该表非常低效。特别是当in IE 8, where rendering tables is extra slow,你必须尽可能少地修改DOM时。
我重构了你的逻辑,通过将元素保存到要重用的变量来最小化查找元素所执行的查找次数。另外,删除了重新呈现表格的.html('...')
调用,而是使用.prepend()
函数将<thead>
添加到<table>
作为第一个孩子。
jQuery.fn.fixGridView = function () {
"use strict";
var start = +new Date(); // log start timestamp
if (this.is('table') && this.children('thead').length === 0) {
var firstRow = this.children('tbody').children('tr:first');
var thead = "<thead><tr>" + firstRow.html() + "</tr></thead>";
firstRow.remove();
this.prepend(thead);
}
var end = +new Date(); // log end timestamp
var diff = end - start;
alert(diff);
return this;
};
$(document).ready(function () {
$('table[id*="gvCategories"]').fixGridView();
});
继续在IE8中测试它:http://jsfiddle.net/amyamy86/4xLzL/7/
答案 1 :(得分:0)