所以我正在尝试使用javascript生成一个注册框,我已经设法这样做,直到我偶然发现了一个奇怪的错误。该脚本在HTML中输出:
<input type="f" name="i" alt="r" placeholder="s">
而不是:
<input type="email" name="regemail" alt="email" placeholder="What's your email?">
其他2个输入也是如此。为什么会这样?我试图寻找任何错误,但控制台没有给我任何错误,我发现我写的代码没有任何错误。感谢帮助。
var firstInput = ["email", "regemail", "email", "What's your email?"];
var secondInput = ["password", "regpassword", "password", "Choose a password"];
var thirdInput = ["password", "confirmpassword", "confirmpassword", "Confirm password"];
var types = ["type", "name", "alt", "placeholder"];
var inputNumber = ["firstInput", "secondInput", "thirdInput"];
var container = document.getElementById('usp-container');
function register() {
var div = document.createElement('div');
div.setAttribute('id', "register-popup");
container.appendChild(div);
var form = document.createElement('form');
form.setAttribute('method', "post");
form.setAttribute('action', "processregistration.php");
div.appendChild(form);
for (i = 0; i < 3; i++) {
function makeInputs(inputs) {
var tableRow = document.createElement('tr');
form.appendChild(tableRow);
var tableData = document.createElement('td');
tableRow.appendChild(tableData);
var input = document.createElement('input');
for (j = 0; j < 4; j++) {
input.setAttribute(types[j], inputs[j]);
}
tableData.appendChild(input);
}
makeInputs(inputNumber[i]);
}
}
register();
答案 0 :(得分:2)
您在数组中有变量名称
var firstInput = ["email", "regemail", "email", "What's your email?"];
var inputNumber = ["firstInput", "secondInput", "thirdInput"];
然后,您将迭代这些变量名称,并尝试使用
获取该变量的值inputNumber[0]
这样就可以获得字符串"firstInput"
,而不是数组,所以当你这样做时
inputNumber[0][0]
你从数组中获得了"f"
,而不是值"email"
。
要使用字符串引用变量,必须使用括号表示法,并在全局范围内使用类似
的字符串window[inputNumber[0]][0];
这实际上不是获取变量的好方法
使用对象
会更好var values = {
firstInput : ["email", "regemail", "email", "What's your email?"],
secondInput : ["password", "regpassword", "password", "Choose a password"],
thirdInput : ["password", "confirmpassword", "confirmpassword", "Confirm password"]
}
然后引用具有键名
的数组values[inputNumber[0]][0]