首页 > 解决方案 > 读取输入值时收到错误“Uncaught TypeError: Cannot read property 'value' of null”

问题描述

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="prompt.css">
    

    <title>The Chat App</title>
</head>
<body>
    <div id="prompt">
        <h1>Please fill in the required information.</h1><br><br>

        <h2>Name that will be shown while chatting:</h2><br>

        <input type="text" placeholder="Enter name">
        <p id = "error label"></p><br>
       <button id = "button" onclick = "Continue();">CONTINUE</button>



    </div>
</body>
<script src = "prompt.js"></script>

</html>

CSS代码:

html{
    padding: 30px;
    text-align: center;
    font-family:  'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background-image: linear-gradient(to right, orange,yellow );
}

#prompt{
    border-radius: 10px;
    background-color:white;
    padding: 17px;
    border:2px solid;
    margin-top: 115px;
    
    box-shadow: 5px 5px 8px  #535352;
}
h1{
    text-decoration: underline;
    font-size: 40px;
    
}
input{
    font-size: larger;
}
button{
    font-size: larger;
    padding:5px 32px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background-color: chartreuse;
    
}
button:focus{
    outline: 0;

}

香草javascript代码:

function Continue(){
    const inputValue = document.getElementById("input").value;
    console.log(inputValue);
}

我正在构建一个提示 html 页面来输入您的信息,但我遇到了一个非常令人沮丧的错误。

当我单击继续按钮时,出现错误:“prompt.js:2 Uncaught TypeError: Cannot read property 'value' of null at Continue (prompt.js:2) at HTMLButtonElement.onclick (prompt.html:20)”

任何帮助将非常感激!!

标签: javascripthtmldom

解决方案


尝试这个 ...

function Continue(){
    const val = document.querySelector('input').value;
    console.log(val)
}
<h1>Please fill in the required information.</h1><br><br>

        <h2>Name that will be shown while chatting:</h2><br>

        <input type="text" placeholder="Enter name">
        <p id = "error label"></p><br>
       <button id = "button" onclick = "Continue()">CONTINUE</button>


推荐阅读