appendchild只能节点,有没有直接拼html代码的方法呢?
<html>
<body>
<ul id="ul1">
<li>jjj</li>
<li>ddd</li>
</ul>
<script>
var html="<li>qqq</li><li>www</li>";
document.getElementsTagName("ul")[0].appendChild(html);
</script>
</body>
</html>
没听说过哦,印象中jQuery
内部的实现是用innerHTML
的方式实现的append
一个字符串的。
所以如果你追求原生,你也可以innerHTML
。
或者我low了
insertAdjacentHTML
<script type="text/javascript">
function append(parent, text) {
if (typeof text === 'string') {
var temp = document.createElement('div');
temp.innerHTML = text;
// 防止元素太多 进行提速
var frag = document.createDocumentFragment();
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
parent.appendChild(frag);
}
else {
parent.appendChild(text);
}
}
window.onload = function() {
var text = '<h4>Welcome!</h4><ul><li>A</li><li>B</li><li>C</li></ul><p>Hello, World</p>';
append(document.body, text);
};
</script>
补充一句,可以不使用fragment,使用原因解释在这:http://mdn.beonex.com/en/DOM/document.createDocumentFragment.html