2011-04-12 67 views
2

我有HTML的测试块,作为一个例子::将字符串作为元素插入到JavaScript的DOM?

的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); 

试图做这样的事情......

但“测试”是不是有效的节点或元素,所以我怎么能添加到元素?

我曾考虑过使用innerHtml,但可能已经存在DOM的表/ tbody的子项。

我一直在探索碎片,但这不是点击!

测试HTML具有TBL:

<table id="scriptsT" name="scriptsT" > 
    <tr> 
    . 
    . 

指针或想法,将不胜感激。

谢谢。

回答

1

制作一个div(或span或其他)并加载您的片段与innerHTML。

var someDiv = document.createElement("div"); 
someDiv.innerHTML = "<tr .... "; 
someParentElement.appendChild(someDiv); 
7

你可以追加到innerHTML

scriptTBL.tBodies[0].innerHTML += test; 

foo += barfoo = foo + bar简写。您也可以通过这种方式简化您的HTML创建代码。使用test += 'html here';

appendChild只接受DOM元素。

+1

为了避免不必要的DOM交互(以及对未封闭标签的陌生性),您应该追加一个字符串变量,然后在完成后使用完整字符串设置innerHTML。 – Zach 2011-04-12 21:24:20

+0

@Zach:是的,'scriptTBL.tBodies [0] .innerHtml + = test'中的'test'应该是最后一个'test'变量......但你指出它是正确的。 – 2011-04-12 21:26:27

+1

我明白了 - 这很有道理。另外,我认为它应该是.innerHTML,而不是.innerHtml。 – Zach 2011-04-12 21:34:27

0

你可以做这样的事情:

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; 

编辑:更新的基础上@扎克的评论。

+0

我认为@Zach意味着不同的东西。 'scriptTBL.innerHtml + = newHtml' *是*'scriptTBL.innerHtml = scriptTBL。innerHtml + newHtml;' – 2011-04-12 21:30:06

+0

@Felix - 是的,这是我做了编辑后(我后来觉得很蠢)的想法,但它看起来更漂亮。 – 2011-04-12 21:34:29