首页 > 解决方案 > 当包含两个变量时,if 语句不起作用

问题描述

我想在 javascript 的帮助下创建一个简单的登录系统。不幸的是,if 语句没有按我的预期工作。按下回车键时页面不会重定向。

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>
   

标签: javascripthtml

解决方案


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>


推荐阅读