javascript - 使用 unshift() 使用 javascript 将表单输入添加到数组

标签 javascript arrays

我正在尝试通过表单将元素添加到数组中。我正在使用 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);
};

其他说明:

  1. 你从来不写</input> 。通常你不会关闭input根本没有标签。如果您正在编写 XHTML(您可能没有),您可以将 /主内input像这样的标签:<input id="input" /> 。但同样,您可能编写的不是 XHTML,而是 HTML。

  2. 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/

相关文章:

javascript - 为什么我不能将 new Array(3) 映射到新值数组中?

javascript - WebSocket 最佳实践

javascript - knockout 中的十进制值舍入问题

javascript - 移动窗口时激活/停用事件

javascript - 将参数传递给 jquery 单击事件中的回调函数

javascript - 根据图像主色更改背景颜色?

php - 如何检查多维数组中的所有值是否为空

C++ - 文件 I/O 和字符数组

python - 如何从无关的嵌套中清除 Python 列表?

javascript - 按组和标题对数组进行排序