/**
*
純JS爲DOM添加html字符串:appendHTML方法和prependHTML方法html
* * http://www.myexception.cn/HTML-CSS/1876216.html
*
* http://www.zhangxinxu.com/wordpress/2013/05/js-dom-basic-useful-method/
* @param {Object} html
*/
HTMLElement.prototype.beforeHTML = function(html) {
// If elements have a native insertAdjacentHTML, use it in four HTML
// insertion functions with more sensible names.
if(document.createElement("div").insertAdjacentHTML) {
this.insertAdjacentHTML("beforebegin", html);
return this;
}
var fragment = fragment(html);
this.parentNode.insertBefore(fragment, this);
// 聽說下面這樣子世界會更清淨
fragment = null;
};
HTMLElement.prototype.appendHTML = function(html) {
// If elements have a native insertAdjacentHTML, use it in four HTML
// insertion functions with more sensible names.
if(document.createElement("div").insertAdjacentHTML) {
this.insertAdjacentHTML("beforeend", html);
return this;
}
var fragment = fragment(html);
this.appendChild(fragment);
// 聽說下面這樣子世界會更清淨
fragment = null;
};
HTMLElement.prototype.prependHTML = function(html) {
// If elements have a native insertAdjacentHTML, use it in four HTML
// insertion functions with more sensible names.
if(document.createElement("div").insertAdjacentHTML) {
this.insertAdjacentHTML("afterbegin", html);
return this;
}
var fragment = fragment(html);
// 插入到容器的前面 - 差別所在
this.insertBefore(fragment, this.firstChild);
// 內存回收?
fragment = null;
};
HTMLElement.prototype.afterHTML = function(html) {
// If elements have a native insertAdjacentHTML, use it in four HTML
// insertion functions with more sensible names.
if(document.createElement("div").insertAdjacentHTML) {
this.insertAdjacentHTML("afterend", html);
return this;
}
var fragment = fragment(html);
this.parentNode.insertBefore(fragment, this.nextSibling);
// 聽說下面這樣子世界會更清淨
fragment = null;
};node
function fragment(html) {
var nodes, divTemp = document.createElement("div"),
fragment = document.createDocumentFragment();
divTemp.innerHTML = html;
// 此時div.childNodes就是咱們須要的節點了
nodes = divTemp.childNodes;
for(var i = 0, length = nodes.length; i < length; i += 1) {
// 容器fragment加載克隆的節點 - 克隆的做用是保證nodes的完整
fragment.appendChild(nodes[i].cloneNode(true));
}
// 聽說下面這樣子世界會更清淨
nodes = null;
divTemp = null;
return fragment;
}app