当包含两个变量时,if语句不起作用

时间:2019-02-24 06:15:52

标签: javascript html

我想借助javascript创建一个简单的登录系统。不幸的是,if语句不符合我的预期。按Enter键时,页面不会重定向。

var objPeople = [
	{studentid: "input1"},
	{studentid: "input2"}
]

var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event){
    for(i = 0; i < objPeople.length; i++){
      if (myInput == objPeople[i].myInput && event.keyCode === 13){
        window.location.href = "www.google.com"; 
      }
    }
  });
<html>
    <head>
        <script LANGUAGE="JavaScript" src="JavaScript.js"></script>
        <title>aaa</title>
    </head>
    <body>
        <input type="text" id="myInput">
    </body>
</html>
   

1 个答案:

答案 0 :(得分:2)

myInput未为您的事件定义,您应该通过在eventListener中添加以下行来获取值。

 let myInput= document.getElementById("myInput").value;

按如下所示更改代码。

var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
  let myInput = document.getElementById("myInput").value;
  for (i = 0; i < objPeople.length; i++) {
    if (myInput == objPeople[i].studentid && event.keyCode === 13) {
      console.log(objPeople[i].studentid);
      window.location.href = "https://www.google.com";
    }
  }
});

修改:示例

var objPeople = [{
    studentid: "input1"
  },
  {
    studentid: "input2"
  }
]

var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
  let myInput = document.getElementById("myInput").value;
  for (i = 0; i < objPeople.length; i++) {
    if (myInput == objPeople[i].studentid && event.keyCode === 13) {
      console.log(objPeople[i].studentid);
      window.location.href = "https://www.google.com";
    }
  }
});
<html>

<head>
  <script LANGUAGE="JavaScript" src="JavaScript.js"></script>
  <title>aaa</title>
</head>

<body>
  <input type="text" id="myInput">
</body>

</html>