用对象字面值编写JavaScript代码,无法添加节点
问题如题:
JS:
window.onload = initAll;
function initAll() {
document.getElementsByTagName("form")[0].onsubmit = nodeChanger;
chgNodes.init();
}
function nodeChanger() {
return chgNodes.doAction();
}
var chgNodes = {
actionType: function() {
var radioButtonSet = document.getElementsByTagName("form")[0].nodeAction;
for(var i = 0;i < radioButtonSet.length;i++) {
if(radioButtonSet[i].checked) {
return i;
}
}
return -1;
},
allGrafs: function() {
return this.nodeChgArea.getElementsByTagName("p");
},
pGrafCt: function() {
return this.allGrafs().length;
},
inText: function() {
return document.getElementById("textArea").value;
},
newText: function() {
return document.createTextNode(this.inText());
},
grafChoice: function() {
return document.getElementById("grafCount").selectedIndex;
},
newGraf: function() {
var myNewGraf = document.createElement("p");
myNewGraf.appendChild(this.newText());
return myNewGraf;
},
oldGraf: function() {
return this.allGrafs().item(this.grafChoice());
},
doAction: function() {
switch(this.actionType()) {
case 0:
this.nodeChgArea.appendChild(this.newGraf());
break;
case 1:
if(this.pGrafCt() > 0) {
this.nodeChgArea.remove Child(this.oldGraf());
break;
}
case 2:
if(this.pGrafCt() > 0) {
this.nodeChgArea.insert Before(this.newGraf(), this.oldGraf());
break;
}
case 3:
if(this.pGrafCt() > 0) {
this.nodeChgArea.replace Child(this.newGraf(), this.oldGraf());
break;
}
default:
alert("No valid action was chosen");
}
document.getElementById("grafCount").options.length = 0;
for(var i = 0;i < this.pGrafCt();i++) {
document.getElementById("grafCount").options[i] = new Option(i + 1);
}
return false;
},
init: function() {
this.nodeChgArea = document.getElementById("modifiable");
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset= utf-8">
<title>Replacing Nodes</title>
</head>
<body>
<form action = "#">
<p><textarea id = "textArea" rows = "5" cols = "30"></textarea></p>
<p><label><input type = "radio" name = "nodeAction">Add node</label>
<label><input type = "radio" name = "nodeAction">Delete node</label>
<label><input type = "radio" name = "nodeAction">Insert before node</label>
<label><input type = "radio" name = "nodeAction">Replace node</label></p>
Paragraph #: <select id = "grafCount"></select>
<input type = "submit" value = "Submit">
</form>
<div id = "modifiable"></div>
<script src = "script05.js"></script>
</body>
</html>