2016-05-16 64 views
0

当我在页面的文本框中输入值时,即使我在文本框中键入“yes”,控制台日志也会在我的if语句中调用else条件。我究竟做错了什么?按下“Enter”键将值打印到控制台日志中

<!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"); 
    } 
} 
+0

的*元素*您可以获取绝不已经等于*字符串*。 – Jasper

回答

4

由于begin指向在<input>元件本身,而不是其内容。你需要得到的价值保持:

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

另外请注意,已经有一个顶级功能called confirm,你可能要考虑重新命名你的,所以你不冲突。

0

JavaScript代码错误。 开始对象是input元素,所以如果你要检查在输入文本,然后调用begin.value 代码:

function confirm(){ 
    var begin= document.getElementById("decision"); 
    if(begin.value == "yes") { 
     console.log("Success!"); 
    } 
    else { 
     console.log("Failure"); 
    } 
} 
相关问题