<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
</head>
<body>
<div><p id="oldnode">JavaScript</p></div>
<a href="javascript:replaceMessage1()"> 将“javascript”换为“HTML”</a><br>
<a href="javascript:replaceMessage2()"> 将“HTML”换为“javascript”</a>
<script type="text/javascript">
function replaceMessage1(){
var newnode=document.createElement("p");
var newnodetext=document.createTextNode("HTML");
newnode.appendChild(newnodetext);
var oldnode=document.getElementById("oldnode");
oldnode.parentNode.replaceChild(newnode,oldnode);
}
function replaceMessage2(){
var newnode=document.createElement("p");
var newnodetext=document.createTextNode("javascript");
newnode.appendChild(newnodetext);
var oldnode=document.getElementById("oldnode");
oldnode.parentNode.replaceChild(newnode,oldnode);
}
</script>
</body>
</html>
在你的代码的基础上稍微改下就可以实现:
<script type="text/javascript"> var newnode=document.createElement("p"); function replaceMessage1(){ var newnodetext=document.createTextNode("HTML"); newnode.appendChild(newnodetext); var oldnode=document.getElementById("oldnode"); oldnode.parentNode.replaceChild(newnode,oldnode); } function replaceMessage2(){ var newn=document.createElement("p"); var newtext=document.createTextNode("javascript"); newn.appendChild(newtext); newnode.parentNode.replaceChild(newn,newnode); } </script>
在你把javascript换成html的时候你的p标签已经被替换了,所以第二次在换回来的时候已经找不到ID为“oldnode”的p标签了,所以会报错也没反映。