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.cnblogs.com/16562653945aa/p/12117280.html