如果我将输入值存储在变量中,为什么它的值始终为空?

Sam*_*uel 3 html javascript variables dom

I\xe2\x80\x99m 试图value从我的<input>属性,以便稍后使用它从特定 API URL 获取数据。

\n\n

问题是我的<input>无论我输入什么内容,我的值始终为空。

\n\n

我尝试使用document.querySelector()document.getElementById(); 两者产生相同的结果。

\n\n
const searchBtn = document.querySelector("#searchBtn");\n//const inpuValue = document.querySelector("#inputField").value;\nconst inputValue = (document.getElementById("inputField")).value;\nconst testing = () => alert(inputValue);\n\nsearchBtn.addEventListener("click", testing);\n
Run Code Online (Sandbox Code Playgroud)\n\n

该警报仅显示为空白,但如果我在 HTML 字段中指定值,则它不会\xe2\x80\x99t。所以我想我\xe2\x80\x99m 触发了正确的按钮和<input>字段。(我使用是alert因为我的浏览器都没有向我显示console.log因为我的浏览器都没有在控制台中

\n

Cri*_*ìna 5

testing每次单击按钮时都会调用

\n\n

相比之下,inputValue变量仅在代码首次执行时、页面加载期间初始脚本评估时评估一次,并且不再评估。输入值存储在变量内,此后永远不会更新。(字符串在 JavaScript 中是不可变的:一旦将字符串存储在变量中,它就不会改变,除非将该变量分配给另一个值。)

\n\n

如果您希望每次单击按钮时都刷新该值,则必须每次都查询该元素:

\n\n
const testing = () => {\n  const inputValue = document.getElementById("inputField").value;\n\n  alert(inputValue);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者您可以只保留对该元素的引用并查询value每次查询属性:

\n\n
const inputElement = document.getElementById("inputField");\nconst testing = () => alert(inputElement.value);\n
Run Code Online (Sandbox Code Playgroud)\n