首页 > 解决方案 > 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);
}

标签: javascriptinput

解决方案


您在控制台中看不到任何内容,因为您在调用脚本时输出输入的值,因此基本上是在页面加载时。此时输入框还没有被填满。那就是console.log不显示任何东西。

例如,您可以在每次用户在输入框中键入时运行您的函数。为此,您将需要一个事件侦听器:

选择您想要“观看”的元素并addEventListener()在其上调用方法。它将事件类型和回调函数作为参数。

最后,在回调函数中,我们通过访问事件的目标来获取输入框的值:e.targete是事件对象和事件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">


推荐阅读