我用javascript和php编写了一个formgenerator ..我对Javascript有点问题
代码在第43行停止。完成for循环后,为什么他也会退出if语句?
的script.js
function addrow(){
var table = document.getElementById('table_actions')
var row = table.insertRow(-1);
addcell(table, row);
}
function addcell(table, row){
// ------Config file -----
var object = new Array();
object[0] = "Text";
object[1] = "Password";
object[2] = "Checkbox";
object[3] = "Radio";
object[4] = "Label";
object[5] = "Textarea";
// --------End Config file -----
for (var i = 0; i < 4; i++) {
console.log(i);
var cell = row.insertCell(i);
if (i == 0){
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', 'beschriftung');
cell.appendChild(input);
} else if (i == 1) {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', 'name');
cell.appendChild(input);
} else if (i == 2) {
var dropdown = document.createElement('select');
for (var i = 0; i < object.length; i++) {
var option = document.createElement('option');
option.text = object[i];
option.value = object[i];
dropdown.options.add(option);
cell.appendChild(dropdown);
}
continue;
} else if (i == 3) {
var checkbox = document.createElement('input');
checkbox.setAttribute('type', 'checkbox');
checkbox.setAttribute('name', 'pflicht');
cell.appendChild(checkbox);
} else {
cell.setAttribute('name', i);
}
}
}
HTML
<form action="site.php" method="post">
<div class="actions">
<table id="table_actions">
<tr>
<th>Beschriftung</th><th>Name</th><th>Objekt</th><th>Pflichtfeld</th>
</tr>
</table>
<div id="click" onclick="addrow()">+</div>
<input type="submit" value="Erstellen!" class="action-btn">
</div>
</form>
请查看here
为什么javascript在第43行的for循环之后退出if语句?
答案 0 :(得分:4)
您在if语句循环中使用相同的变量i
,因此最后它是object.length
。
for (var i = 0; i < 4; i++) {
if (i == 0) {
...
} else if (i == 2) {
for (var i = 0; i < object.length; i++) {
...
}
// Now i === object.length
} ...
}
不得不环顾四周,但这个答案为您提供了一些可以使用的细节:
答案 1 :(得分:2)
内部循环损坏,用于主循环的i
计数器:
} else if (i == 2) {
var dropdown = document.createElement('select');
// this :
//for (var i = 0; i < object.length; i++) {
// its needs to be changed to `j` for example, like:
for (var j = 0; j < object.length; j++) {
var option = document.createElement('option');
option.text = object[j]; // also i references needs to be changed to j
option.value = object[j]; // also i references needs to be changed to j
dropdown.options.add(option);
cell.appendChild(dropdown);
}
continue;