您的位置:首页 > 移动开发

getAttribute,appendChild,removeChild,replaceChild,insertBefore 自定义函数

2011-11-08 18:23 337 查看
标题中的三个函数的优化:

1.getAttribute 因getAttribute在IE与Firefox上有会区别,比如class,for上面,获取到的值不一样

2.appendChild只能每次添加一个,不能添加多个

3.removeChild只能每次移除一个,不能移除多个

4.replaceChild,insertAfter(与insertBefore对应)

为了兼容,因此创建此函数:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>test</title>
<script language="javascript">
window.onload = function() {
var op = document.getElementById('op');
var header= document.getElementById('header');
var div1 = document.createElement("div");
div1.innerHTML="DIV1";
var div2 = document.createElement("div");
div2.innerHTML="DIV2";
var div3 = document.createElement("div");
div3.innerHTML="DIV3";

//如下为获取节点op的class属性,IE/Firefox均可得到 base,调用函数getAttr()
alert(getAttr(op,"class"));
//如下为将div1,div2,div3三个DIV添加到document.body中,调用函数append()
append(document.body,div1,div2,div3);
//如下为将div1,div2,div3三个DIV移除从document.body中,调用函数delNode()
delNode(div1,div2,div3);
//如下,将节点op换成新的div1,op为原节点,div1为新节点,调用函数replaceNode()
replaceNode(op,div1);
//如下,将div1节点插入到header节点之后,调用函数insertAfter()
insertAfter(header,div1);
};

function insertAfter(node,newNode) {
//将newNode插入到node之后
//如果node有下一个节点,newNode插入到node.nextSibling的前面
//如果node没有下一个节点,newNode插入到node.parentNode.appendChild的后面
var pn = node.parentNode;
if (node.nextSibling) {
pn.insertBefore(newNode,node.nextSibling);
} else {
pn.appendChild(newNode);
}
return newNode;
}

function replaceNode(replaced,newNode) {
replaced.parentNode.replaceChild(newNode,replaced);
}

function each(arr,fn) {
for (var i=0;i<arr.length;i++) {
fn(arr[i],i);
}}

function delNode() {
/*for (var i=0;i<arguments.length;i++) {
arguments[i].parentNode.removeChild(arguments[i]);
}*/
each(arguments,function(node){
node.parentNode.removeChild(node);
});
}

function append(node) {
for (var i=1;i<arguments.length;i++) {
node.appendChild(arguments[i]);
}
return node;
}

var specialNames={
"class":"className",
"for":"htmlFor"
};
function getAttr(node,attrName) {
var attr = node.getAttribute(attrName);
if (attr == null) {
if (attrName in specialNames) {
attrName = specialNames[attrName];
attr = node.getAttribute(attrName);
}
}
return attr
}

</script>
</head>
<body>
<h1 id="header">TEST</h1>
<p id="op" class="base">第一段</p>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: