[英]Inserting String as Elements to the DOM for javascript?
我有一個HTML測試塊,作為一個例子::
HTML是一個字符串,而不是DOM元素,但我試圖看看是否有方法,或者可以用來將字符串作為DOM插入的方法,因此它可以附加到DOM。
var test='<tr class="rowHeaders">';
test=test+'<td id="sTD" name="sTD" width="4%">test.php</td>'
test=test+'<td width="2%"><input type="radio" name="tb" ></td>';
test=test+'<td id="tTD" name="tTD" width="2%">php</td>';
test=test+'<td width="2%"><input type="button" name="vv" ></td>';
test=test+'</tr>';
var scriptTBL=document.getElementById("scriptsT");
scriptTBL.children[0].appendChild(test);
試着做這樣的事......
但是“test”不是一個有效的節點或元素,所以如何將它添加到元素?
我想過使用innerHtml,但是DOM的表/ tbody可能已經有了一個子節點。
我一直在探索片段,但這不是點擊!
測試html有tbl:
<table id="scriptsT" name="scriptsT" >
<tr>
.
.
指針或想法將不勝感激。
謝謝。
你可以附加到innerHTML
:
scriptTBL.tBodies[0].innerHTML += test;
foo += bar
是foo = foo + bar
簡寫。 您也可以通過這種方式簡化HTML創建代碼。 使用test += 'html here';
。
appendChild
只接受DOM元素。
創建div
(或span
或其他)並使用innerHTML加載片段。
var someDiv = document.createElement("div");
someDiv.innerHTML = "<tr .... ";
someParentElement.appendChild(someDiv);
你可以這樣做:
var test = '<tr class="rowHeaders">';
test = test + '<td id="sTD" name="sTD" width="4%">test.php</td>'
test = test + '<td width="2%"><input type="radio" name="tb" ></td>';
test = test + '<td id="tTD" name="tTD" width="2%">php</td>';
test = test + '<td width="2%"><input type="button" name="vv" ></td>';
test = test + '</tr>';
var discardableElement = document.createElement("div");
discardableElement.innerHtml = test;
var scriptTBL = document.getElementById("scriptsT");
scriptTBL.tBodies[0].appendChild(discardableElement.firstChild);
這有點浪費,因為你創建一個DOM元素(這是一個昂貴的操作)只是為了丟棄它,但它會創建DOM元素以允許你使用appendChild
方法。
或者,您可以使用字符串連接來使用innerHtml屬性,如下所示:
var test = '<tr class="rowHeaders">';
test = test + '<td id="sTD" name="sTD" width="4%">test.php</td>'
test = test + '<td width="2%"><input type="radio" name="tb" ></td>';
test = test + '<td id="tTD" name="tTD" width="2%">php</td>';
test = test + '<td width="2%"><input type="button" name="vv" ></td>';
test = test + '</tr>';
var scriptTBL = document.getElementById("scriptsT");
// Insert at the BOTTOM of the table
var newHtml = scriptTBL.innerHtml + test;
// OR... Insert at the top of the table
//var newHtml = test + scriptTBL.innerHtml;
scriptTBL.tBodies[0].innerHtml = newHtml;
編輯:根據@Zach的評論更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.