首页 > 代码库 > 利用父子级来修改数据:previousSibling,parentNode,nextSibling

利用父子级来修改数据:previousSibling,parentNode,nextSibling

function adit(obj) {
//var demoA = document.getElementById("operation");
var demoA = obj;
var a = demoA.parentNode.previousSibling;//这个parentNode找到的是<td>标签的同一级父级点,

                      //也就是其他两个<td>加空白,

                      //previousSibling(这个是向上找同一父级点的子节点)
while(a != null) {
if(a.nodeType == 1) {
a.innerHTML = ‘<input type="text" value="http://www.mamicode.com/‘+a.innerText+‘">‘;
}
a = a.previousSibling;
}
demoA.parentNode.innerHTML = ‘<a href="http://www.mamicode.com/#" onclick="save(this)" id="operation">save</a>‘;
}

function save(obj) {
//var demoA = document.getElementById("operation");
//用obj自定义的来代替document.getElementById("operation")
var demoA = obj;
var a = demoA.parentNode.previousSibling;
while(a != null) {
if(a.nodeType == 1) {
var x = getFirstChild(a);
a.innerHTML = x.value;
}
a = a.previousSibling;
}
demoA.parentNode.innerHTML = ‘<a href="http://www.mamicode.com/#" id="operation" onclick="adit(this)">edit</a>‘;
}

//参数:输入所有的节点包括空白

//返回值:找到下一节点不是空白的节点
function getFirstChild(dom,nodeType) {
nodeType = nodeType || 1;//默认如果不输入nodeType,则nodeType值为1;也就是不是空白节点;
var x = dom.firstChild;
while(x.nodeType != nodeType) {
x = x.nextSibling;//找x的下一个节点
}
return x;
}

<html>

<head>

<meta charset="utf-8">
</meta>
</head>
<body>
<table border="1" style="width:100%">
<tr>
<th>姓名</th>
<th>邮箱</th>
<th>操作</th>
</tr>
<tr>
<td>operation</td>
<td>operation@qq.com</td>
<td><a href="http://www.mamicode.com/#" id="operation" onclick="adit(this)">edit</a></td>
</tr>
<tr>
<td>operation</td>
<td>operation@qq.com</td>
<td><a href="http://www.mamicode.com/#" id="operation" onclick="adit(this)">edit</a></td>
</tr>
<tr>
<td>operation</td>
<td>operation@qq.com</td>
<td><a href="http://www.mamicode.com/#" id="operation" onclick="adit(this)">edit</a></td>
</tr>
<tr>
<td>operation</td>
<td>operation@qq.com</td>
<td><a href="http://www.mamicode.com/#" id="operation" onclick="adit(this)">edit</a></td>
</tr>
</table>
</body>
<script src="http://www.mamicode.com/js/main.js">
</script>
</html>

 

效果图

技术分享

 

技术分享

技术分享

利用父子级来修改数据:previousSibling,parentNode,nextSibling