Javascript 数组 - 全局范围的问题



我不知道为什么这不起作用。在第一个函数中将项添加到数组中,但在第二个函数中无法访问(尽管声明数组时添加的项存在(。我认为与数组的全局范围有关,但我可以看到如何让它工作。

var theArray = ["apple"];
function addValue() {
var myValue = document.forms["myAdd"]["myInput"].value;
theArray.push(myValue);
alert(theArray[theArray.length - 1]);
/*works ok*/
}
function getValue() {
alert(theArray[theArray.length - 1]);
/*returns 'apple', not last item pushed on array*/
}
<h1>Array example</h1>
<form name="myAdd" onsubmit="return addValue()" method="post">
Add to array: <input type="text" name="myInput">
<input type="submit" value="Go">
</form>
<p>Get from array</p>
<form name="myGet" onsubmit="return getValue()" method="post">
<input type="submit" value="Go">
</form>

提交表单的默认操作是重新加载页面(如果表单具有action=属性,请将位置更改为该属性(。

重新加载页面将导致内存中任何保存的值(即变量(被擦除。有一些方法可以解决这个问题,比如使用localStorage,但我怀疑您并不打算让表单的默认行为占据主导地位。

为此,我们在事件对象上有一个preventDefault()方法:

var theArray = ["apple"];
var addForm = document.getElementById('add-form');
var getForm = document.getElementById('get-form');
addForm.addEventListener('submit', addValue);
getForm.addEventListener('submit', getValue);
function addValue(event) {
event.preventDefault(); // Stops the form submission
var myValue = document.forms["myAdd"]["myInput"].value;
theArray.push(myValue);
alert(theArray[theArray.length - 1]);
}
function getValue(event) {
event.preventDefault();
alert(theArray[theArray.length - 1]); // Now works as expected.
}
<h1>Array example</h1>
<form id="add-form" name="myAdd" method="post">
Add to array: <input type="text" name="myInput">
<input type="submit" value="Go">
</form>
<p>Get from array</p>
<form id="get-form" name="myGet" method="post">
<input type="submit" value="Go">
</form>

请注意我是如何从表单元素中删除onsubmit=属性的,使用on*=属性被认为是不好的做法,因为它们会迫使您的代码变得比它需要的更全局。

相反,我给了它们 ID 以便于在 DOM 中找到(您可以使用任何其他方法,您只需要对表单 DOM 元素的引用(,并在它们上调用addEventListener

最新更新