[英]How to insert a a set of table rows after a row in pure JS
我有以下問題:我需要在X行之后插入N行。我需要插入的行集作為由TR元素組成的HTML塊傳遞給我的函數。 我還可以訪問TR,之后需要插入。
這與我之前用另一個TBODY代替TBODY之前所做的稍有不同。
我遇到的問題是appendChild
需要單個元素,但是我必須插入一個集合。
編輯:
這是解決方案 :
function appendRows(node, html){
var temp = document.createElement("div");
var tbody = node.parentNode;
var nextSib = node.nextSibling;
temp.innerHTML = "<table><tbody>"+html;
var rows = temp.firstChild.firstChild.childNodes;
while(rows.length){
tbody.insertBefore(rows[i], nextSib);
}
}
看到實際效果:
當我在最后位置以外的任何地方插入一行時,這對我來說要好得多,
var rowNode = refTable.insertRow(0); var cellNode = rowNode.insertCell();
altCognito所說的,只是要注意一個大的innerHTML tbody錯誤 ,以防您想立即使用innerHTML替換所有內容,因為您要這樣做很多,而DOM操作卻太慢了。
IE使用innerHTML插入行時出現錯誤,因此將無法正常工作。 直接從馬的嘴巴上: http : //www.ericvasilik.com/2006/07/code-karma.html
我建議只更新tbody,但將您的代碼附加到新結構中。
使用表對象,您可以在其中插入新行。
var tbl = document.getElementById(tableBodyId);
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
它將在表格末尾插入一行。
if(node.nextSibling && node.nextSibling.nodeName.toLowerCase() === "tr")
這是用來干嘛的? 我認為您不需要它。 如果node.nextSibling為null,則沒有關系。 您可以將其傳遞給insertBefore,其作用與appendChild相同。
無論如何,除了“ tr”外,tbody中沒有其他元素。
for(var i = 0; i < rows.length; i++){
tbody.insertBefore(rows[i], node.nextSibling);
這不適用於多行。 一旦完成一個insertBefore,node.nextSibling現在將指向您剛剛插入的行; 您最終將以相反的順序插入所有行。 您需要記住原始的nextSibling。
ETA:另外,如果“ rows”是活動的DOM NodeList,則每次將其中一行插入新主體時,都會將其從舊主體中刪除! 因此,您在遍歷列表時將銷毀該列表。 這是“其他每個人”錯誤的常見原因:您處理列表的項目0,然后將其從列表中刪除,將項目1下移到項目0所在的位置。 接下來,訪問新項目1,即原始項目2,而原始項目1永遠不會被看到。
可以在普通的非實時“數組”中復制列表,或者,如果您知道它將成為實時列表,則實際上可以使用更簡單的循環形式:
var parent= node.parentNode;
var next= node.nextSibling;
while (rows.length!=0)
parent.insertBefore(rows[0], next);
我必須插入一組。
通常,當您考慮一次插入一組元素時,您希望使用DocumentFragment。 但是,不幸的是,您無法在DocumentFragment上設置“ innerHTML”,因此您必須在上面的表格中設置行,然后將它們逐一移入DocumentFragment,然后在documentFragment之前插入。 盡管從理論上講,這可能比追加到最終目標表中要快(由於對childNodes進行列表重擊的次數較少),但實際上,通過我的測試,實際上並沒有明顯快得多。
另一種方法是insertAdjacentHTML,這是僅IE的擴展方法。 不幸的是,由於IE錯誤,您無法在tbody的子代上調用insertAdjacentHTML,就像您無法設置tbody.innerHTML一樣。 您可以在DocumentFragment中設置它:
var frag= document.createDocumentFragment();
var div= document.createElement(div);
frag.appendChild(div);
div.insertAdjacentHTML('afterEnd', html);
frag.removeChild(div);
node.parentNode.insertBefore(frag, node.nextSibling);
不幸的是,出於某種神秘的原因,insertAdjacentHTML在這種情況下以某種方式工作非常緩慢。 上述方法對我來說大約是一對一insertBefore速度的一半。 :-(
您需要將它們一個接一個地添加。
您需要確定X行是否為最后一行...
//determine if lastRow...
//if not, determine row_after_row_x
for(i in n_rows){
if(lastRow){
tbodyObj.appendChild(row_i_of_n);
} else {
tbodyObj.insertBefore(row_i_of_n, row_after_row_x);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.