如果将输入存储在变量中,为什么输入的值始终为空? [英] Why is the value of my input always empty if I store it in a variable?

查看:72
本文介绍了如果将输入存储在变量中,为什么输入的值始终为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从我的< input> 字段中获取 value 属性,以便以后使用

I’m trying to get the value property from my <input> field so I can later use it to fetch data from a specific API URL.

问题是我的< input> 值始终是

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

I tried to use document.querySelector() and document.getElementById(); both yield the same result.

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 )。

The alert just appears blank, but it doesn’t if I specify a value in the HTML field. So I guess I’m triggering the right button and <input> field. (I use alert because none of my browsers show me the console.log in the console).

推荐答案

每次单击按钮都会调用 testing 函数处理程序。

The testing function handler is called every time the button is clicked.

相反, inputValue 变量在首次执行代码时仅被评估一次,在页面加载期间的初始脚本评估中,再也不会。输入值存储在变量内部,此后再也不会更新。 (字符串在JavaScript中是不可变的:将字符串存储在变量中后,除非您将该变量分配给另一个值,否则它将不会更改。)

In contrast, the inputValue variable is evaluated only once when the code is firstly executed, at initial script evaluation during page load, and never again. The input value gets stored inside the variable and it never gets updated after that. (Strings are immutable in JavaScript: once you store a string in a variable, it won’t change unless you assign that variable to another value.)

如果要每次单击按钮都刷新值,则每次都必须查询元素:

If you want to refresh the value every time you click the button, you have to query the element every time:

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

  alert(inputValue);
}

或者您可以保留对元素的引用并查询<$ c每次$ c> value 属性:

Or you can keep just a reference to the element and query the value property every time:

const inputElement = document.getElementById("inputField");
const testing = () => alert(inputElement.value);

这篇关于如果将输入存储在变量中,为什么输入的值始终为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆