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

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

问题描述

我正在尝试从我的 <input> 字段中获取 value 属性,以便我以后可以使用它从特定的 API URL 获取数据.

问题是我的 值总是空的,不管我输入什么.

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

const searchBtn = document.querySelector("#searchBtn");//const inpuValue = document.querySelector("#inputField").value;const inputValue = (document.getElementById("inputField")).value;const 测试 = () =>警报(输入值);searchBtn.addEventListener("click", testing);

警报只是显示为空白,但如果我在 HTML 字段中指定值,则不会显示.所以我想我正在触发右键和 字段.(我使用 alert 因为我的浏览器都没有在控制台中显示 console.log).

解决方案

testing 函数处理程序在每次点击按钮时被调用.

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

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

const testing = () =>{const inputValue = document.getElementById("inputField").value;警报(输入值);}

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

const inputElement = document.getElementById("inputField");const 测试 = () =>警报(输入元素.值);

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.

The problem is that my <input> value is always empty no matter what I type in it.

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

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

解决方案

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

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);
}

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天全站免登陆