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
相关产品推荐
相关产品推荐

