使用unshift()使用javascript将表单输入添加到数组 [英] Add form input to array with javascript using unshift()
问题描述
我正在尝试通过表单将元素添加到数组。我正在使用unshift()方法。以下代码无效,我想知道为什么。
I am trying to add elements to an array via a form. I am using the unshift() method. The code below doesn't work and I would like to know why.
<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
操作将导致''
,警报将为空白。
Your quoted code runs immediately when the page is loaded. The form field won't have anything in it then, so its value will be ''
. When you alert that, the default toString
operation on the array will result in ''
and the alert will be blank.
您想运行 unshift
代码来响应用户事件,例如单击按钮,而不是比马上。您可以通过将 input
设置为元素(从该行中删除 .value
)然后移动您的行来实现通过 unshift
进入要分配给 onclick
的函数,并添加 .value
那里:
You want to run your unshift
code in response to a user event, such as the button being clicked, rather than right away. You can do that by setting input
to be the element (remove .value
from that line) and then moving your line with unshift
into the function you're assigning to onclick
, adding the .value
there:
button.onclick = function alerted (){
myArray.unshift(input.value);
alert(myArray);
};
其他说明:
-
您永远不会写
< / input>
。通常,您根本不会关闭input
标记。如果您正在编写XHTML(可能不是),则将/
放入主输入
中这样的代码:< input id = input />
。但同样,您可能不是在编写XHTML,而只是在编写HTML。
You never write
</input>
. Normally you don't closeinput
tags at all. If you're writing XHTML (you probably aren't), you'd put the/
within the maininput
tag like this:<input id="input" />
. But again, you're probably not writing XHTML, just HTML.
输入$ c的值(标题) $ c>按钮位于其
value
属性中,而不位于开始和结束标记之内。 (您应该使用带有 button
元素的开始和结束标签,而不是 input
的元素。)
The value (caption) of an input
button goes in its value
attribute, not content within opening and closing tags. (You would use opening and closing tags with the button
element, not input
.)
Taking all of that together, here's a minimalist update: 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>
这篇关于使用unshift()使用javascript将表单输入添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!