You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS点击按钮向数组添加字符串时遇到的问题

问题原因

你的按钮放在<form>标签内,默认是submit类型,点击后会触发表单提交,导致页面刷新。页面刷新后所有JS变量都会重新初始化,所以arrayWords又变回了初始的['bill', 'sam'],看起来像是没添加成功。而console.log(tmpWord)能短暂显示,是因为刷新前这行代码已经执行了。

解决办法

有两种简单的修复方式:

方式一:阻止表单默认提交行为

修改JS代码,在点击事件里阻止表单的默认刷新行为:

let arrayWords = ['bill', 'sam'];

document.querySelector('button').addEventListener('click', addWord);

function addWord(event) {
  // 阻止表单提交导致的页面刷新
  event.preventDefault();
  tmpWord = document.querySelector('input').value;
  console.log(tmpWord);
  arrayWords.push(tmpWord);
  // 在这里打印数组,就能看到更新后的内容了
  console.log(arrayWords);
}

console.log(arrayWords); // 这行只会打印初始数组

方式二:修改按钮类型

直接把HTML里的按钮类型改成button,这样它就不会触发表单提交:

<h1>Enter a new word in the box below. Type "stop" to exit.</h1>
<form>
  <input type="text">
  <button type="button">submit</button>
</form>

另外提醒:原来的console.log(arrayWords)是页面加载时执行的,只会输出初始数组。要查看更新后的数组,要么在addWord函数里打印,要么页面不刷新时在浏览器控制台手动输入arrayWords查看。

内容的提问来源于stack exchange,提问作者s_m_lima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:02:08