簡體   English   中英

有沒有快速通過jQuery刪除表行的方法

[英]Is there a fast way to .remove table rows with jQuery

我有一個50個奇數行,11列的表格。 每行都有一個唯一的idid="row_<clientid>_rownumber" 第二列中有一個復選框,其中id="group_<clientid>_<petid>_rownumber"

編輯截圖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);

謝謝你們

你可以先為客戶存儲行,

var clientRow = $('#row_' + sClient);

然后清空桌子

$('#table_id tbody').empty();

然后插回行

$('#table_id tbody').append(clientRow);

這將不會循環,所以它的恆定時間

首先,給表一個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();

我想你可以嘗試使用.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上面的回答不同,這些都不能保證更快,但它們是使這項工作的不同方式,並且IE可能更快。

絕對是你的表的id並將其用作你的jQuery上下文。 還存儲表jQuery對象 - 盡管你可能不會看到很多改進。 我可能會嘗試將一個類應用於每一行。 例如,為每一行提供他們所屬的客戶端類。 然后,這應該做的伎倆:

var tableElement = $("#table_id"); // only do this once on page load
tableElement.find("tr:not(." + sClient + ")").hide();

不能保證這會更快,但值得一試。

我首先要在表格中添加一個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)實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM