[英]Javascript just doesn't redirect, reloads index.html instead
因此,我正在尝试制作一个小的虚拟登录表单,当我单击一个按钮时,它会将我重定向到另一个页面。 但这不是,而是再次重新加载index.html。
HTML(编辑):
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form action="" class="form-horizontal">
<div class="modal-header">
<h4>Log In</h4>
</div> <!-- End of Modal Header -->
<div class="modal-body">
<div class="form-group">
<label for="login-name" class="col-lg-2 control-label">Username</label>
<div class="col-lg-10">
<input type="text" placeholder="Enter Your Username" class="form-control" id="login-name">
</div>
</div> <!-- End of -->
<div class="form-group">
<label for="login-name" class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" placeholder="Enter Your Password" class="form-control" id="login-name">
</div>
</div> <!-- End of -->
<div class="form-group">
<button class="btn btn-default pull-right btn-large" id="loginBtn" style="margin-right: 20px;">Login</button>
</div> <!-- End of -->
</div> <!-- End of Modal Body -->
<div class="modal-footer">
<a href="#" class="btn btn-default btn-xs">Forgot Password</a>
<a href="#" class="btn btn-default btn-xs">Sign Up</a>
<a href="#" class="btn btn-default btn-xs" data-dismiss="modal">Close</a>
</div> <!-- End of Modal footer -->
</form>
</div> <!-- End of Modal Content -->
</div> <!-- End of Modal Dialog -->
</div> <!-- End of Modal Fade LOGIN -->
JS:
window.addEventListener("load",init, false);
function init() {
var loginBtn = document.getElementById("loginBtn");
loginBtn.addEventListener("click", checkLogin, false);
}
function checkLogin(e) {
alert("FIRED");
if(1>0){
window.location.href = "//www.google.com";
}
}
起初我以为它可能没有重定向,因为它根本没有调用该函数,但是确实可以。 每次都会触发警报,但随后仅重新加载页面。
当我告诉它在init函数中执行此操作时,它也可以重新定位。 我要去哪里错了?
<button>
元素的默认行为是执行提交动作。 由于您没有取消它,因此正在提交表单,而您对location.href
所做的更改将被忽略。 由于您尚未为action=""
指定值,因此提交只会刷新当前页面。
可以避免这种情况的三种不同方式:
type="button"
: <button class="btn btn-default pull-right btn-large"
id="loginBtn" style="margin-right: 20px;" type="button">Login</button>
type="button"
的input
: <input class="btn btn-default pull-right btn-large" value="Login"
id="loginBtn" style="margin-right: 20px;" type="button" />
function checkLogin(e) {
e.preventDefault();
alert("FIRED");
if(1>0){
window.location.href = "//www.google.com";
}
}
您还可以使用一种更简单的方式,我更喜欢在button标签中使用window.location.href,如下所示:
<button class="Whatever you want to call it" onclick="window.location.href='The_Page_You_Want_To_Redirect_To.html'"></button>
然后您可以根据需要使用CSS设置按钮样式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.