当我在页面上的文本框中输入一个值时,即使我在文本框中键入“是”,控制台日志也会在if语句中调用else条件。我究竟做错了什么?

<!DOCTYPE html>
<html>
    <head>
        <title> Choose your own adventure </title>
        <meta charset= "utf-8">
        <script src= "choose1.js"></script>
        <link type= "text/css" rel= "stylesheet" href= "choose1.css"/>
    </head>
    <body>
        <p> What do you do? </p>
            <input type= "text" id= "decision" name= "decision" onkeydown=  "if(event.keyCode === 13) confirm()" />
        </p>
    </body>
</html>

//choose1.js//
function confirm(){
    var begin= document.getElementById("decision");
    if(begin === "yes") {
        console.log("Success!");
    }
    else {
        console.log("Failure");
    }
}

最佳答案

因为begin指向<input>元素本身,而不是其内容。您需要掌握价值:

var begin= document.getElementById("decision").value;


另外,请注意,已经有一个顶级功能called confirm,您可能要考虑重命名您的名称,以免发生冲突。

关于javascript - 按“Enter”将值打印到控制台日志,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37250239/

10-09 17:04