基本上,我设计了一个小的登录页面,但我的检查功能无法正常工作。
我创建了div元素和一个函数来通过Javascript中的ID对其进行检查。但是它不能正常工作当该功能应该检查“用户并通过”中的值时,它说“用户名或密码无效”
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<header id="header">Please Login Here</header>
<meta charset="utf-8">
<title id="title">Login</title>
</head>
<body>
<form>
<div id="user">
<input type="text" name="user" placeholder="Username">
</div>
<div id="pass">
<input type="text" name="pass" placeholder="Password">
</div>
<script type="text/javascript">
function check() {
if (document.getElementById("user") == "Guy" && (document.getElementById("pass")) == "123") {
alert("Welcome!")
} else {
alert("Invalid username or password!")
}
}
</script>
<div id="login">
<button type="button" name="button" onclick="check()">Login!</button>
</div>
</body>
预期结果是“欢迎光临!”输入正确的内容后,在警报框中输入: 用户名:Guy 密码:123
答案 0 :(得分:3)
您需要在输入元素上使用.value
-因此请使用querySelector
。还要检查您的括号嵌套:
function check() {
if (document.querySelector("#user > input").value == "Guy" && document.querySelector("#pass > input").value == "123") {
alert("Welcome!")
} else {
alert("Invalid username or password!")
}
}
<div id="user">
<input type="text" name="user" placeholder="Username">
</div>
<div id="pass">
<input type="text" name="pass" placeholder="Password">
</div>
<div id="login">
<button type="button" name="button" onclick="check()">Login!</button>
</div>
答案 1 :(得分:1)
您获得ID用户为id的元素dev和ID为pass的元素dev,然后验证用户名和密码 您应该阅读用户文本框和密码文本框的值,然后验证该方式
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<header id="header">Please Login Here</header>
<meta charset="utf-8">
<title id="title">Login</title>
</head>
<body>
<form>
<div>
<input type="text" Id="user" name="user" placeholder="Username">
</div>
<div>
<input type="text" id="pass" name="pass" placeholder="Password">
</div>
<script type="text/javascript">
function check() {
debugger;
if (document.getElementById("user").value == "Guy" && (document.getElementById("pass").value) == "123") {
alert("Welcome!")
} else {
alert("Invalid username or password!")
}
}
</script>
<div id="login">
<button type="button" name="button" onclick="check()">Login!</button>
</div>
</body>
答案 2 :(得分:-1)
我做了个大清洁
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<script>
function check() {
var user = document.getElementById("user").value;
var pass = document.getElementById("pass").value;
if ( user == "Guy" && pass == "123") {
alert("Welcome!")
} else {
alert("Invalid username or password!")
}
}
</script>
</head>
<body>
<header>Please Login Here</header>
<form>
<input id="user" type="text" name="user" placeholder="Username">
<input id="pass" type="password" name="pass" placeholder="Password">
<button type="submit" onclick="check()">Login!</button>
</form>
</body>
</html>