当我在页面上的文本框中输入值时,即使我在文本框中键入“yes”,控制台日志也会调用 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/