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

标签 javascript html variables dom

我正在尝试获取 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/

相关文章:

html - 通过XPath获取包装元素

javascript - 单击按钮将 <div> 的内容添加到文本框

variables - 从批处理文件中的变量中删除双引号会导致 CMD 环境出现问题

python - 修改 Python 函数中的变量会影响函数外部具有不同名称的变量

javascript - node.js rsa 加密/解密

javascript - 使用 javascript 添加 <use> 标签

javascript - Selenium IDE : How to verify <TD> Contents when it contains a mix of tags and <BR> breaks

html - 匹配不包含特定值的 HTML 表行 ( <tr> ) 的正则表达式