为什么将textarea值登录到函数中时始终为空? [英] Why is the textarea value always empty when log it in a function?

查看:33
本文介绍了为什么将textarea值登录到函数中时始终为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在文档中呈现textarea值后将其呈现在文档中,

I’m trying to get the textarea value using JavaScript after it is rendered in the document, I used:

let input = document.getElementById("input").value;
let btn = document.getElementById("btn");

btn.addEventListener("click", () => {
  console.log(input);
};

但是它一直在控制台中显示一个空字符串.

But it keeps on showing an empty string in the console.

推荐答案

请下次也添加您的HTML.

Please add your HTML as well next time.

也就是说,在您的代码中,页面加载时,输入的值只能读取一次.如果要读取和显示更新的输入值,则每次按下该按钮时都必须读取它.下面是一个简单的示例:

That said, in your code the value of your input is read only once when the page is loaded. If you want to read and display the updated input value you have to read it every time the button is pressed. A simple example here below:

let btn = document.getElementById("btn");
btn.addEventListener("click", () => {
  let input = document.getElementById("input").value;
  console.log(input);
});

<input id="input"></input>
<button id="btn">PressMe</button>

这篇关于为什么将textarea值登录到函数中时始终为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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