DOM操作的增强版功能函数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 将一个DOM节点、HTML字符串混合型参数 | |
* 转化为原生的DOM节点数组 | |
* | |
* */ | |
function checkElem(a) { | |
var r = []; | |
if (a.constructor != Array) { | |
//如果不是参数数组,则强行转换 | |
a = [a]; | |
} | |
for (var i = 0; i < a.length; i++) { | |
//如果是字符串,例如"<li>aa</li>" | |
if (a[i].constructor == String) { | |
//使用一个临时元素来存放HTML | |
var div = document.createElement("div"); | |
//注入HTML,转换成DOM结构 | |
div.innerHTML = a[i]; | |
for (var j = 0; j < div.childNodes.length; j++) { | |
r[r.length] = div.childNodes[j]; | |
} | |
} else if (a[i].length) { | |
//假定是DOM节点数组 | |
for (var j = 0; j < a[i].length; j++) { | |
r[r.length] = a[i][j]; | |
} | |
} else { | |
//DOM节点 | |
r[r.length] = a[i]; | |
} | |
} | |
return r; | |
} | |
/** | |
* 在parent执行环境下,在before元素下前面添加elem元素 | |
* */ | |
function before(parent, before, elem) { | |
//检查是否提供parent节点参数 | |
if (elem == null) { | |
elem = before; | |
before = parent; | |
parent = before.parentNode; | |
} | |
//获取元素的新数组 | |
var elems = checkElem(elem); | |
/** | |
* 向后遍历数组, | |
* 因为我们向前插入元素 | |
* */ | |
for (var i = elems.length - 1; i >= 0; i--) { | |
parent.insertBefore(elem[i], before); | |
} | |
} | |
/** | |
* 为parent追加一个子元素的辅助函数 | |
* | |
* */ | |
function append(parent, elem) { | |
var elems = checkElem(elem); | |
for(var i = 0; i <= elems.length; i++){ | |
parent.appendChild(elems[i]); | |
} | |
} | |
/** | |
* 删除elem节点函数 | |
* | |
* */ | |
function remove(elem) { | |
if(elem) { | |
elem.parentNode.removeChild(elem); | |
} | |
} | |
/** | |
* 从一个元素中删除所有子节点的函数 | |
* | |
* */ | |
function empty(elem) { | |
while(elem.firstChild) { | |
remove(elem.firstChild); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment