javascript - JS输入值分配给变量 - 未定义
问题描述
我真的很新鲜JS
需要一些帮助,因为我什么都不懂。如果我尝试将整行分配给变量,我可以稍后使用此变量,但是当我尝试将其记录到控制台时,结果是空白或未定义,或者警告使用 opera/chrome 它仍然是同样,我做错了吗?
HTML
<input type="text" id="name" placeholder="username">
JS
不工作
var name = document.getElementById('name').value;
console.log(name);
也不能这样做
var name = document.getElementById('name');
console.log(name.value);
内部HTML不起作用
我只能这样做
console.log(document.getElementById('name').value);
将代码更新为完整示例 所以我将变量名称更改为 nameInp 但它不起作用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<input type="text" id="name" placeholder="podaj imię">
<input type="text" id="name2">
<input type="text" id="name3">
<!--
<input type="password" id="password" placeholder="podaj hasło">
<input type="password" id="confPassword" placeholder="powtórz hasło">
-->
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
<!--
<p id="para"></p>
-->
<div class="center"></div>
<div class="center2"></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="main.js"></script>
</body>
</html>
var nameInp = document.getElementById('name').value;
var btn = document.getElementById('submit');
function check(){
console.log(nameInp);
}
解决方案
您在控制台中看不到任何内容,因为您在调用脚本时输出输入的值,因此基本上是在页面加载时。此时输入框还没有被填满。那就是console.log
不显示任何东西。
例如,您可以在每次用户在输入框中键入时运行您的函数。为此,您将需要一个事件侦听器:
选择您想要“观看”的元素并addEventListener()
在其上调用方法。它将事件类型和回调函数作为参数。
最后,在回调函数中,我们通过访问事件的目标来获取输入框的值:e.target
。e
是事件对象和事件e.target
的属性target
。
console.log()
每次用户在输入框中输入时,下面的代码都会调用 a :
document.querySelector('#username').addEventListener('keydown', function (e) {
console.log(e.target.value);
});
<input type="text" id="username" placeholder="username">
推荐阅读
- php - 如何在 PHP Laravel 中从 Authorize.net 获取卡交易的最后四位数字
- javascript - 用javascript中的数组值替换字符串
- python - 在python中使用@符号
- unit-testing - 比较具有忽略项目顺序的切片字段的结构与stretchr/testify
- php - PHP COM(Html to docx) $word->ActiveDocument->SaveAs() 有 Uncaught com_exception: 参数 0: 类型不匹配
- ruby-on-rails - 在 rails upgrade 迁移条目从模式迁移表中删除后
- javascript - 具有反应映射功能但“未定义”的导入数组
- javascript - 如何在不重置组件的情况下更改按钮的表情符号?
- javascript - 用于 Python 2/Ignition 的具有 2 个不同分隔符的 CSV 数据
- javascript - 使用 Javascript React 创建网格