我正在尝试通过表单将元素添加到数组中。我正在使用 unshift() 方法。下面的代码不起作用,我想知道为什么。
<form>
<input id="input"> </input>
<input type = "button" id="button"> Click me </input>
</form>
<script>
var input = document.getElementById("input").value;
var button = document.getElementById("button");
var myArray = [];
myArray.unshift(input);
button.onclick = function alerted (){
alert(myArray);
};
</script>
最佳答案
当页面加载时,您引用的代码将立即运行。表单字段中将没有任何内容,因此其值将是 ''
。当您发出警报时,默认 toString
对数组的操作将导致 ''
并且警报将为空白。
您想要运行 unshift
代码响应用户事件,例如单击按钮,而不是立即响应。您可以通过设置 input
来做到这一点成为元素(从该行中删除 .value
),然后使用 unshift
移动您的行进入您分配给 onclick
的函数,添加 .value
那里:
button.onclick = function alerted (){
myArray.unshift(input.value);
alert(myArray);
};
其他说明:
你从来不写
</input>
。通常你不会关闭input
根本没有标签。如果您正在编写 XHTML(您可能没有),您可以将/
主内input
像这样的标签:<input id="input" />
。但同样,您可能编写的不是 XHTML,而是 HTML。input
的值(标题)按钮进入其value
属性,而不是开始和结束标记中的内容。 (您可以将开始和结束标记与button
元素一起使用,而不是input
。)
将所有这些放在一起,这是一个简约的更新:Live copy | source
<form>
<input id="input"><!-- No ending tag -->
<input type = "button" id="button" value="Click me"><!-- No ending tag, move value where it should be -->
</form>
<script>
var input = document.getElementById("input"); // No .value here
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // Moved this line, added the .value
alert(myArray);
};
</script>
关于javascript - 使用 unshift() 使用 javascript 将表单输入添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12903927/