从标记字符串创建节点 [英] Create node from markup string
本文介绍了从标记字符串创建节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在JavaScript中将标记字符串转换为节点对象?实际上我正在寻找这个分类:
Is there a way to convert markup string to node object in JavaScript? Actually I am looking for the subsitute for:
document.getElementById("divOne").innerHTML += "<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"
像
document.getElementById("divOne").appendChild(document.createNodeFromString("<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"))
使用createNodeFromString创建表元素,然后附加其子元素,然后附加各自的属性和值!
using createNodeFromString rather creating the table element then append its child elements then attach their respective attributes and values!
推荐答案
这个没有现有的跨浏览器功能。可以使用以下方法来实现所需的效果(使用 基于 >这个答案
):
There's not an existing cross-browser function for this. The following method can be used to achieve the desired effect (using a DocumentFragment
for an optimized performance, based on this answer):
function appendStringAsNodes(element, html) {
var frag = document.createDocumentFragment(),
tmp = document.createElement('body'), child;
tmp.innerHTML = html;
// Append elements in a loop to a DocumentFragment, so that the browser does
// not re-render the document for each node
while (child = tmp.firstChild) {
frag.appendChild(child);
}
element.appendChild(frag); // Now, append all elements at once
frag = tmp = null;
}
用法(可读性缩写):
appendStringAsNodes(
document.getElementById("divOne"),
"<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"
);
这篇关于从标记字符串创建节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文