纯JS为DOM添加html字符串:appendHTML方法和prependHTML方法
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; };
转自:http://www.zhangxinxu.com/wordpress/2013/05/js-dom-basic-useful-method/
相关推荐
Enbiting 2020-06-11
chenjinlong 2020-06-03
AndroidGA 2020-06-01
PrisonJoker 2020-04-16
绿豆饼 2020-02-02
magic00 2020-01-29
magic00 2019-12-28
SIMONDOMAIN 2020-01-01
若不使用模块控制器或Include_Controller调用,Test Fragment是不执行的。Test Fragment主要是用来进行脚本重用。默认新建的Test Fragment,是禁用状态。
Cherishyuu 2019-12-11
learnNG 2019-12-11
luoj 2013-07-08
laose0 2013-07-08
绿豆饼 2019-10-28
LXLYHM 2015-03-25
wangruoze 2015-03-23
wangkuifeng0 2016-01-15
najiutan 2014-03-04
sunnylin 2019-07-01