JavaScript - 将输入框的值添加到数组中

8

目标是将另一个项目添加到数组中,并使其像["Car", "House", "Boat"]等一样。

问题在于,当我控制台记录时,我的数组中只有一个项目,而不是我从表单提交的所有值。

这是我的表单

<form onsubmit="guardarNumeros()">
 <p>Please insert the items</p>
 <input type="text" id="box">
 <input type="submit" value="Submit">
</form>

我的js

function guardarNumeros(){

 var items = [];
 boxvalue = document.getElementById('box').value;
 items.push(boxvalue);  
 console.log(items);

}

谢谢您!

你只需要推送单个项。那么你如何输入这些值呢? - Sebastian Simon
你的意思是用户在“框”输入字段中输入多个值吗?那么这是否涉及将字符串拆分为标记? - Patrick Hund
同时您需要将<form onsubmit="return guardarNumeros()">写入代码,并在函数末尾添加 return false; 以避免在页面重新加载时出现空项目。 - mplungjan
每次调用 guardarNumeros 函数时,您都会重新定义数组......所以...... - epascarello
感谢您的帮助! - Hugo Seleiro
3个回答

13

你的 items 数组在 guardarNumeros 函数的作用域内,并且每次调用 guardarNumeros 都会声明它,如果你想让它持久存在,就需要将其放在外部:

你的items数组在guardarNumeros函数的作用域内。如果你希望它保留下来,则需要将其放到函数外部。

var items = [];

function guardarNumeros() {
  boxvalue = document.getElementById('box').value;
  items.push(boxvalue);  
  console.log(items);
}

如在评论中所述,表单提交默认会刷新页面,为了防止这种情况发生,您需要返回false:

<form onsubmit="return guardarNumeros()">

function guardarNumeros() {
  boxvalue = document.getElementById('box').value;
  items.push(boxvalue);  
  console.log(items);
  return false;
}

非常感谢您的帮助! - Hugo Seleiro
我刚刚使用这个答案解决了自己的问题。我在函数外部调用了等效变量 boxvalue,导致数组中出现空字符串。 - Dannyw24

2

你需要在函数外部声明数组,因为每当你点击提交按钮时,一个新的数组对象就被创建了,而之前的数组会因为作用域而丢失。

如果我们在任何函数内部声明变量,那么这个变量只能在该函数内部可见。在该函数外部,我们无法访问它。在你的情况下,你在函数内部声明了一个数组,然后向其中添加值并记录它。但是,如果你尝试从函数外部访问这个数组,在严格模式下会出现错误。

只需在全局范围内声明数组,或者你也可以将数组作为参数传递。这将解决你的问题。

var items = [];

function guardarNumeros(){

 boxvalue = document.getElementById('box').value;
 items.push(boxvalue);  
 console.log(items);

}

或者使用这种方法。但是请确保您在调用此函数的父级函数中的任何位置声明了数组。
function guardarNumeros(items){

     boxvalue = document.getElementById('box').value;
     items.push(boxvalue);  
     console.log(items);

    }

在这种情况下,您还需要检查一些条件...

谢谢你的帮助! - Hugo Seleiro

2
通过将项目包含在函数的范围内,您每次都在声明数组。 http://plnkr.co/edit/mGLCT97QwM8CvD3I5yUp?p=preview

var items = [];

function guardarNumeros() {
  boxvalue = document.getElementById('box').value;
  items.push(boxvalue);
  console.log(items);
  return false; // stop submission
}
<form onsubmit="return guardarNumeros()">
  <p>Please insert the items</p>
  <input type="text" id="box">
  <input type="submit" value="Submit">
</form>


感谢您的帮助! - Hugo Seleiro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接