我有一个50个奇数行,11列的表格。每行都有一个由id
组成的唯一id="row_<clientid>_rownumber"
。第二列中有一个带有id="group_<clientid>_<petid>_rownumber"
Redacted Screenshot http://www.forsythesit.com.au/res/img/slowrowremoval.jpg
当用户单击复选框时,我想删除除属于所选客户端的所有行。我的代码如下:
var sClient = $(this).attr("id").substring(6); // trim off group_
sClient = sClient.substring(0,sClient.indexOf("_")); // trim off anything after clientid
$("tr[id^=row_]").not("tr[id^=row_" + sClient + "]").remove();
问题是需要很长时间才能在IE中得到“脚本耗时过长”的警告。
是否有更快的方法可以删除多行?
顺便说一句:使用jQuery 1.4.3需要4.4秒,使用jQuery 1.4.2需要1.3秒
问题解决了所有人。最终提示由@VisusZhao提供。这是最后的工作片段:
var KeepRows = $("#bookingstable tbody tr[id^=row_" + sClient + "_]");
$("#bookingstable tbody").empty();
$("#bookingstable tbody").append(KeepRows);
谢谢大家
答案 0 :(得分:2)
您可以先存储客户端的行,
var clientRow = $('#row_' + sClient);
然后清空表
$('#table_id tbody').empty();
然后将行重新插入
$('#table_id tbody').append(clientRow);
这将不会循环,所以它的常数时间
答案 1 :(得分:1)
首先,请为表格提供一个ID。
<table id="departures">
将所有必需的行存储在jQuery对象中,并且仅存储在#departures
内的所有行。
var $departures = $("#departures");
var $rows = $("tr[id^=row_]", $departures); //
这样,每次执行函数时jQuery都不必遍历DOM,因为它将存储在对象中。
然后像往常一样使用您的代码
var sClient = $(this).attr("id").substring(6); // trim off group_
sClient = sClient.substring(0,sClient.indexOf("_")); // trim off _row
用此
替换最后一行$rows.not("tr[id^=row_" + sClient + "]", $departures).remove();
答案 2 :(得分:0)
我认为您可以尝试使用.filter
,例如:
var sClient = this.id.substring(6); // trim off group_
$("#table_id tr").filter(function(){
return (this.id.indexOf('row') === 0 && this.id !== sClient);
}).remove();
或者,也许,给每个客户端的行一个类:
var sClient = this.id.substring(6); // trim off group_
$('#table tr.' + sClient).remove();
与上面的Marko's answer不同,这些保证都不会更快,但它们是使这项工作的不同方式,并且对于IE可能更快。
答案 3 :(得分:0)
绝对识别您的表并将其用作您的jQuery上下文。还存储表jQuery对象 - 尽管你可能不会看到很多改进。我可能会尝试将一个类应用于每一行。例如,为每一行提供他们所属的客户端类。然后,这应该做的伎俩:
var tableElement = $("#table_id"); // only do this once on page load
tableElement.find("tr:not(." + sClient + ")").hide();
不能保证这会更快,但可能值得一试。
答案 4 :(得分:0)
我首先要在表格中添加一个ID:
<table id="alldepartures">
接下来,对于每一行,如果需要,请保留id
,但也要添加“client_ {id}”格式的CSS类:
<tr class="client_123">
这没关系,因为您可以拥有多个具有相同类的行。
然后在你的代码中:
var sClient = $(this).attr("id").split('_')[1];
//remove all rows that don't have this class
$('#alldepartures').find('tr[class!=client_' + sClient + ']').remove();
我认为其他代码可能特别在IE中受到影响,尝试基于ID进行匹配,因为jQuery必须在IE中做额外的工作来克服他们错误的getElementById(id)实现。