为啥将斜体变为粗体就不行?
求诸位大神详解
2016-09-25
replaceChild(newnode,oldnode)每次使用的时候,所有与之相关的属性内容被清空,也就是说你第一次替换之后,那个位置的id属性已经清空了,变成了<i>JavaScript</i>,你已经无法通过oldnode=document.getElementById("oldnode")获取节点了,所以每次替换着以后你要给替换上的节点添加id属性,具体如下面代码
--------------------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>childNodes</title>
</head>
<body>
<script type="text/javascript">
function replaceMessage(){
var change=document.getElementById("change");
var oldnode=document.getElementById("oldnode");
if (oldnode.nodeName=="B"){
var newnode=document.createElement("i");
newnode.innerHTML=oldnode.innerHTML;
oldnode.parentNode.replaceChild(newnode,oldnode);
oldnode=null;
newnode.setAttribute("id","oldnode");
change.innerHTML="斜体改粗体";
}
else {
var newnode=document.createElement("b");
newnode.innerHTML=oldnode.innerHTML;
oldnode.parentNode.replaceChild(newnode,oldnode);
oldnode=null;
newnode.setAttribute("id","oldnode");
change.innerHTML="粗体改斜体";
}
}
</script>
<b id="oldnode">Java</b><br>
<a href="javascript:replaceMessage()" id="change">粗体改斜体</a>
</body>
</html>
举报