我对关闭注册表单使用了相同的方法,它起了作用,但对于登录表单,它不起作用——任何人都知道问题可能是什么?
function openSignInForm(){
document.getElementById('loginform').style.display="block";
}
function closeSignInForm(){
document.getElementById('loginform').style.display="none";
}
<div id=loginform >
<form method="post" action="loginForm.php">
<?php include('errors.php'); ?>
<div class="col-md-12">
<label for="username" class="form-label">Username</label>
<input type="text" name="username" class="form-control" >
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" name="password" >
</div>
<div class="d-grid gap-2">
<div class="btn-group" role="group" aria-label="Basic mixed styles example">
<button class="btn btn-outline-success" name="login_user">Log In</button>
<button class="btn btn-outline-success" onclick="closeSignInForm()">Close</button>
</div>
</div>
</form>
</div>
openSignInForm按钮工作,但关闭按钮不工作。包含表单的div不显示,因此在默认情况下,它将被隐藏,直到用户单击按钮。
试试这个:
<html>
<body>
<div>
<form id="loginform" method="post" action="loginForm.php">
<?php include('errors.php'); ?>
<div class="col-md-12">
<label for="username" class="form-label">Username</label>
<input type="text" name="username" class="form-control" />
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" name="password" />
</div>
<div class="d-grid gap-2">
<div
class="btn-group"
role="group"
aria-label="Basic mixed styles example"
>
<button
class="btn btn-outline-success"
name="login_user"
type="submit"
>
Log In
</button>
</div>
</div>
</form>
<button class="btn btn-outline-success" id="b1" type="button"></button>
</div>
<script type="text/javascript">
let button = document.getElementById("b1");
let form = document.getElementById("loginform");
button.innerHTML = "Open";
button.addEventListener("click", toogle);
let form_open = false;
form.style.display = "none";
function toogle() {
if (form_open) {
form.style.display = "none";
button.innerHTML = "Open";
form_open = false;
} else {
form.style.display = "block";
button.innerHTML = "Close";
form_open = true;
}
}
</script>
</body>
</html>
尝试用以下代码替换关闭按钮代码:
<button class="btn btn-outline-success" onclick="closeSignInForm(this)">Close</button>
和你的closeSignInForm
函数
function closeSignInForm(e){
e.preventDefault();
document.getElementById('loginform').style.display="none";
}
表单上的按钮默认提交表单。您可以将<button>
的type
属性设置为"button"
以防止这种情况:
<button class="btn btn-outline-success" type="button" onclick="closeSignInForm()">Close</button>
在点击处理程序中调用event.preventDefault()
也会停止自动提交,请参阅Amit Sharma的回答。