<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
window.onload = function() {
//测试replaceChild()方法
var bjNode = document.getElementById("bj");
var xyjNode = document.getElementById("xyj");
var cityNode = document.getElementById("city");
//cityNode.replaceChild(xyjNode, bjNode);
//节点互换
var bookNode = document.getElementById("book");
/*
var bjNode2 = bjNode.cloneNode(true);//true表示可以克隆子节点
bookNode.replaceChild(bjNode2, xyjNode);
cityNode.replaceChild(xyjNode, bjNode)
*/
replaceEach(bjNode, xyjNode);
}
//自定义互换函数
function replaceEach(aNode, bNode){
//alert(1);
//1.获取aNode bNode的父节点
var aParent = aNode.parentNode;
var bParent = bNode.parentNode;
if(aParent && bParent){
var aNode2 = aNode.cloneNode(true);
//cityNode.replaceChild(newChild, oldChild);
bParent.replaceChild(aNode2, bNode);
aParent.replaceChild(bNode, aNode);
}
}
</script>
</head>
<body>
<p>你喜欢哪个城市?</p>
<ul id="city">
<li id="bj" name="beijing">北京</li>
<li>上海</li>
<li>武汉</li>
<li>深圳</li>
</ul>
<p>你喜欢哪本书?</p>
<ul id="book">
<li id="xyj" name="xyj">西游记</li>
<li>三国演义</li>
<li>水浒传</li>
</ul>
<br />
<form action="#" name="myForm">
<input type="radio" name="type" value="city"/>城市
<input type="radio" name="type" value="book"/>BOOK
<input type="text" name="myName"/>
<input type="submit" value="submit" id="submit"/>
</form>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
//实现city和book对应子节点的互换
window.onload = function() {
//JS里没有局部变量和全局变量概念
//获取所有的li节点
var liNodes = document.getElementsByTagName("li");
var length = liNodes.length;
//为li节点添加onclick方法
for(var i= 0; i < liNodes.length; i++){
//每个li节点添加一个index属性
liNodes[i].index = i;
liNodes[i].onclick = function(){
var targetIndex = 0;
//length必须为偶数,否则会出问题
if(this.index < length/2){
targetIndex = length/2 + this.index;
}else{
targetIndex = this.index - length/2;
}
//alert(liNodes[targetIndex].firstChild.nodeValue);
//交换index属性
//alert(this.index);
var tempIndex = this.index;
this.index = liNodes[targetIndex].index;
liNodes[targetIndex].index = tempIndex;
replaceEach(this, liNodes[targetIndex]);//交换两个节点及事件
}
}
}
//自定义互换函数
function replaceEach(aNode, bNode){
//alert(1);
//1.获取aNode bNode的父节点
var aParent = aNode.parentNode;
var bParent = bNode.parentNode;
if(aParent && bParent){
var aNode2 = aNode.cloneNode(true);
//克隆aNode节点时把aNode的onclick事件也克隆
aNode2.onclick = aNode.onclick;
//克隆index
aNode2.index = aNode.index;
//cityNode.replaceChild(newChild, oldChild);
bParent.replaceChild(aNode2, bNode);
aParent.replaceChild(bNode, aNode);
}
}
</script>
</head>
<body>
<p>你喜欢哪个城市?</p>
<ul id="city">
<li id="bj" name="beijing">北京</li>
<li>上海</li>
<li>深圳</li>
<li>深圳2</li>
</ul>
<p>你喜欢哪本书?</p>
<ul id="book">
<li id="xyj" name="xyj">西游记</li>
<li>三国演义</li>
<li>水浒传</li>
<li>水浒传2</li>
</ul>
<br />
</body>
</html>
转载于:https://blog.51cto.com/shamrock/1564665