输入登录详细信息后,我希望将target.html页面加载到同一窗口中。当前,它会加载到新标签中。
<body>
<div class="loginbox">
<img src="images/avatar.png" class="avatar">
<h1>Login</h1>
<form>
<p>Username</p>
<input type="text" name="userid" placeholder="Enter Username">
<p>Password</p>
<input type="password" name="pswrd" placeholder="Enter Password">
<input type="submit" onclick="check(this.form)" value="Login">
</form>
<script language="javascript">
function check(form) {
if (form.userid.value == "username" && form.pswrd.value == "password") {
window.open('target.html')
} else {
alert("Error Password or Username")
}
}
</script>
</div>
</body>
答案 0 :(得分:1)
window.location.href = 'target.html';
由于该按钮位于表单中,因此还必须使用e.preventDefault()
取消事件的默认行为。这是一个完整的示例:
function check(e) {
e.preventDefault();
if (e.target.form.userid.value == "username" && e.target.form.pswrd.value == "password") {
window.location.href = 'target.html';
} else {
alert("Error Password or Username")
}
}
<div class="loginbox">
<img src="images/avatar.png" class="avatar">
<h1>Login</h1>
<form>
<p>Username</p>
<input type="text" name="userid" placeholder="Enter Username">
<p>Password</p>
<input type="password" name="pswrd" placeholder="Enter Password">
<input type="submit" onclick="check(event)" value="Login">
</form>
</div>
答案 1 :(得分:0)
您可以保留type =“ submit”并使用:
form.addEventListener('submit', function(event) {
event.preventDefault();
if (form.userid.value == "username" && form.pswrd.value == "password") {
window.open('target.html', '_self');
} else {
alert("Error Password or Username");
}
}, false);