目标是在数组中添加另一个项目,并创建一个像["Car","House","Boat"]等数组.
发生的事情是当我控制日志时,我的数组中只有一个项目,而不是我从表单提交的所有值.
这是我的表格
<form onsubmit="guardarNumeros()">
<p>Please insert the items</p>
<input type="text" id="box">
<input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)
我的js
function guardarNumeros(){
var items = [];
boxvalue = document.getElementById('box').value;
items.push(boxvalue);
console.log(items);
}
Run Code Online (Sandbox Code Playgroud)
谢谢 !
你的items数组在你的guardarNumeros函数范围内,并且每次guardarNumeros调用都会被声明,如果你想要它持久化它需要在外面:
var items = [];
function guardarNumeros() {
boxvalue = document.getElementById('box').value;
items.push(boxvalue);
console.log(items);
}
Run Code Online (Sandbox Code Playgroud)
如评论中所述,表单提交将默认刷新页面,以防止您需要返回false:
<form onsubmit="return guardarNumeros()">
Run Code Online (Sandbox Code Playgroud)
function guardarNumeros() {
boxvalue = document.getElementById('box').value;
items.push(boxvalue);
console.log(items);
return false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16398 次 |
| 最近记录: |