简体   繁体   English

无法获取 JavaScript 中输入字段的值

[英]Can’t get value of input field in JavaScript

For some reason JavaScript does not give me the value option of my input field.出于某种原因 JavaScript 没有给我输入字段的值选项。 It gives me the value of my button however, so something must be wrong with my input.但是,它给了我按钮的值,所以我的输入一定有问题。

This is my code HTML: <input type=“number” id=“inputs” /> JS: Const input = document.getElementById(“inputs”).value这是我的代码 HTML: <input type=“number” id=“inputs” /> JS: Const input = document.getElementById(“inputs”).value

Try console.log(e) on your return function.在返回 function 时尝试console.log(e)

This is easier to do in React, but my solution to this problem has been to look at the object on the next level up.这在 React 中更容易做到,但我对这个问题的解决方案是查看下一级的 object。

Hence why you are looking for e instead of e.target where the latter is your button element.因此,为什么您要寻找e而不是e.target ,后者是您的按钮元素。

The solution will probably look something like e.target.value[0][1] , as the object returns a nested collection of objects.该解决方案可能类似于e.target.value[0][1] ,因为 object 返回一个嵌套的对象集合。

if you are trying to get value of input when it's changed you have to add event listener.如果您试图在输入更改时获取输入值,则必须添加事件侦听器。

<input placeholder="Enter some text" name="name" />
<p id="values"></p>


const input = document.querySelector('input');
const log = document.getElementById('values');

input.addEventListener('input', updateValue);

function updateValue(e) {
  log.textContent = e.target.value;
}

ref from HTMLElement来自HTMLElement的引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM