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

问题描述 投票:0回答:1

我正在尝试从我的

value
字段中获取
<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>
字段。 (我使用
alert
因为我的浏览器都没有在控制台中向我显示
console.log
)。

javascript html variables dom
1个回答
5
投票

每次单击按钮时都会调用

testing
函数处理程序。

相比之下,

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

如果每次点击按钮都想刷新值,那么每次都要查询元素:

const testing = () => {
  const inputValue = document.getElementById("inputField").value;

  alert(inputValue);
}

或者您可以只保留对元素的引用并每次查询

value
属性:

const inputElement = document.getElementById("inputField");
const testing = () => alert(inputElement.value);
© www.soinside.com 2019 - 2024. All rights reserved.