jQuery append() 方法中可以直接添加字符,如:$("p").append(" <b>Hello world!</b>");
怎么用js实现呢:
appendHTML:
HTMLElement.prototype.appendHTML = function(html) { var divTemp = document.createElement("div"), nodes = null // 文档片段,一次性append,提高性能 , fragment = document.createDocumentFragment(); divTemp.innerHTML = html; nodes = divTemp.childNodes; for (var i=0, length=nodes.length; i<length; i+=1) { fragment.appendChild(nodes[i].cloneNode(true)); } this.appendChild(fragment); // 据说下面这样子世界会更清净 nodes = null; fragment = null; };
prependHTML:
var prependHTML = function(el, html) { var divTemp = document.createElement("div"), nodes = null , fragment = document.createDocumentFragment(); divTemp.innerHTML = html; nodes = divTemp.childNodes; for (var i=0, length=nodes.length; i<length; i+=1) { fragment.appendChild(nodes[i].cloneNode(true)); } // 插入到容器的前面 - 差异所在 el.insertBefore(fragment, el.firstChild); // 内存回收? nodes = null; fragment = null; };
转自:https://www.iteye.com/blog/shenchuochuo-2197445
$("p").append(" <b>Hello world!</b>")
;
纯JS为DOM添加html字符串:appendHTML方法和prependHTML方法
原文:https://www.cnblogs.com/7qin/p/12117251.html