<script type="text/javascript">
var a = new Array();
function obj(type, value) {
this.type = type;
this.value = value;
this.toStr = toStr
}
function toStr() {
if (this.type == "select") {
var temp = "";
var arr = this.value.split("/");
for (i = 0; i < arr.length; i++) {
temp += "<option>" + arr[i] + "</option>"
}
return "<select>" + temp + "</select><br>";
} else
return "<input type = '" + this.type + "' value = '" + this.value + "'><br>";
}
function addObj(type) {
var sel = parent.frames["left"].document.form1.q.value;
for (i = 0; i < sel; i++)
a[a.length] = new obj(type,
parent.frames["left"].document.form1.caption_text.value,
a.length);
paint();
parent.frames["left"].document.form1.caption_text.value = "";
}
function paint() {
parent.frames["right"].document.open()
for (i = 0; i < a.length; i++)
parent.frames["right"].document.writeln(a[i].toStr())
parent.frames["right"].document.close()
}
</script>
<form name=form1>
<table>
<tr>
<td><input type="button" style="width: 150px" value="Add Button" onClick="addObj('button')"><br />
<input type="button" style="width: 150px" value="Add TexBox" onClick="addObj('text')" /><br />
<input type="button" style="width: 150px" value="Add Select" onClick="addObj('select')" /></td>
<td>Text : <br /> Number of adding elements:<br /></td>
<td><input type="text" name="caption_text" style="width: 150px"> <br /> <select
NAME=q size=1 style="width: 150px">
<option selected value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
</table>
</FORM>
创建选择元素时代码损坏。 这段代码出了什么问题?
提前致谢。
答案 0 :(得分:1)
您的i
个变量缺少var
声明。所有循环使用相同的计数器,这意味着嵌套循环将破坏可怕。我的建议是:
var a = [];
function FormElement(type, value) {
this.type = type;
this.value = value;
}
FormElement.prototype.toString = function toStr(){
if (this.type == "select") {
var arr = this.value.split("/");
for (var i = 0; i < arr.length; i++) {
arr[i] = "<option>" + arr[i] + "</option>"
}
return "<select>" + arr.join("") + "</select><br />";
} else
return "<input type = '" + this.type + "' value = '" + this.value + "' /><br />";
};
function addObj(type) {
var form = parent.frames["left"].document.form1;
var sel = form.q.value;
for (var i = 0; i < sel; i++)
a.push(new FormElement(type, form.caption_text.value);
paint();
form.caption_text.value = "";
}
function paint() {
var doc = parent.frames["right"].document;
doc.open();
doc.write(a.join("\n"));
doc.close();
}