我有以下页面带有javascript文件,当用户输入错误的用户名/密码消息"错误的用户名密码"输出到页面;但是,该消息不会保留在页面上。由于某种原因,页面会刷新。
<html>
<head>
<script src="letmein.js"></script>
</head>
<body>
<h1 id="h1">JavaScript Test Page</h1>
<p id="p">Click the link to login into the application</p>
<p>login</p>
<form id="myForm" name="myForm" onSubmit="letmein();">
<p>username:
<input type="text" name="username">
</p>
<p>password:
<input type="text" name="password">
</p>
<input type="submit" value="Login">
</form>
<p id="hidden"></p>
<a href="#" onClick="clear();">clear</a>
</body>
</html>
javascript文件
var username = "admin";
var password = "letmein";
var counter = 0;
//login form authentication
function letmein() {
var formUser = document.forms['myForm']['username'].value;
var formPass = document.forms['myForm']['password'].value;
if(formUser === username && formPass === password) {
window.open("file:///home/jorge/usersearch.html");
}
counter++;
document.getElementById("hidden").innerHTML = "Wrong username or password!"
if(counter === 3) {
alert("Access Denied!");
}
}
//close window
function closeWindow() {
close();
};
答案 0 :(得分:0)
我认为点击按钮会提交表单。您需要在onSubmit上返回false,以避免提交表单。
<html>
<head>
<script src="letmein.js"></script>
</head>
<body>
<h1 id="h1">JavaScript Test Page</h1>
<p id="p">Click the link to login into the application</p>
<p>login</p>
<form id="myForm" name="myForm" onSubmit="letmein(); return false;">
<p>username:
<input type="text" name="username">
</p>
<p>password:
<input type="text" name="password">
</p>
<input type="submit" value="Login">
</form>
<p id="hidden"></p>
<a href="#" onClick="clear();">clear</a>
</body>
</html>
答案 1 :(得分:0)
您需要停止表单的默认操作。例如:
function letmein(e) {
if(validationFails) {
e.preventDefault(); //this will stop the form from submitting
}
}