[英]My page wont redirect to url using a function
So I have a project, which needs to have a sample login page, using this it was working but now it is not opening the url in the If statement所以我有一个项目,它需要一个示例登录页面,使用它可以工作,但现在它没有在 If 语句中打开 url
function validate() {
var usern = document.getElementById("userIn").value;
var passw = document.getElementById("passIn").value;
var position = -1;
var usernArray = ["User1", "User2"];
var passwArray = ["Pass1", "Pass2"];
for (var i=0; i <usernArray.length; i++) {
if ((usern == usernArray[i]) && (passw == passwArray[i])) {
position = i;
break;
}
}
if (position != -1)
{
alert("Login Was Successful!, You are being redirected to the homepage");
window.location.href = 'home.html';
}
else
{
alert("Invalid Username and/or Password! Please try again.")
}
}
Could you try this window.location.href=/home.html
so it is relative to the current domain.你能试试这个window.location.href=/home.html
所以它是相对于当前域的。 Or you could try the window.location.replace instead of href.或者您可以尝试使用 window.location.replace 代替 href。
You can solve this by adding to the button on your form the attribute: type="button"您可以通过将属性添加到表单上的按钮来解决此问题: type="button"
<button type="button" onclick="validate()">Login</button>
and your code will work perfectly, but notice that you need to consider the form being submitted also (by pressing Enter button on keyboard).并且您的代码将完美运行,但请注意您还需要考虑提交的表单(通过按键盘上的Enter按钮)。 Maybe try changing your code to this:也许尝试将您的代码更改为:
<script>
$('#form').on('submit', function(e) {
var usern = document.getElementById("userIn").value;
var passw = document.getElementById("passIn").value;
var position = -1;
var usernArray = ["User1", "User2"];
var passwArray = ["Pass1", "Pass2"];
for (var i=0; i <usernArray.length; i++) {
if ((usern == usernArray[i]) && (passw == passwArray[i])) {
position = i;
break;
}
}
if (position != -1)
{
alert("Login Was Successful!, You are being redirected to the homepage");
window.location.href = 'home.html';
}
else
{
alert("Invalid Username and/or Password! Please try again.")
}
e.preventDefault();
return false;
});
</script>
and set the type attribute to your button to submit并将 type 属性设置为您的按钮以提交
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.