我正在尝试获取 value
我的属性(property) <input>
字段,以便我稍后可以使用它从特定 API URL 获取数据。
问题是我的<input>
无论我输入什么内容,值始终为空。
我尝试使用document.querySelector()
和document.getElementById()
;两者产生相同的结果。
const searchBtn = document.querySelector("#searchBtn");
//const inpuValue = document.querySelector("#inputField").value;
const inputValue = (document.getElementById("inputField")).value;
const testing = () => alert(inputValue);
searchBtn.addEventListener("click", testing);
警报只是显示为空白,但如果我在 HTML 字段中指定值,则不会显示空白。所以我想我触发了正确的按钮和 <input>
field 。 (我使用 alert
因为我的浏览器都没有在控制台中向我显示 console.log
)。
最佳答案
每次单击按钮时都会调用 testing
函数处理程序。
相比之下,inputValue
变量仅在代码首次执行时、页面加载期间的初始脚本评估时评估一次,并且不再评估。输入值存储在变量内,此后永远不会更新。 (字符串在 JavaScript 中是不可变的:一旦将字符串存储在变量中,它就不会改变,除非将该变量分配给另一个值。)
如果你想每次点击按钮时都刷新该值,则必须每次都查询该元素:
const testing = () => {
const inputValue = document.getElementById("inputField").value;
alert(inputValue);
}
或者您可以只保留对元素的引用并每次查询 value
属性:
const inputElement = document.getElementById("inputField");
const testing = () => alert(inputElement.value);
关于javascript - 如果我将输入值存储在变量中,为什么它的值始终为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58078160/