javascript - 当包含两个变量时,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>
解决方案
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>
推荐阅读
- mule - 在 Mule 4 中声明动态数据编织变量,就像我们在 Mule 3 中所做的那样
- android - 如何修复“java.lang.IllegalStateException:无法从 CursorWindow 读取第 0 行,第 2 列。”
- ruby-on-rails - 如何为以下代码创建 RSpec 测试
- keras - Keras 学习乘以二的问题
- c++ - 如果未输入 getline 分隔符,推荐一种引发异常的方法?
- python-3.x - 如何运行具有包含换行符的参数的进程?
- java - 我想在什么时候输入一个可选的“错误号码。再试一次”
- java - 如何打印出具有缩进的代码以实际具有缩进?
- django - Django 模型数据过滤器
- python-3.x - xgboost plot_tree(model) - 修复 TypeError: super(type, obj) when Running