JS中的“删除”类有一个奇怪的问题。我有一个带有"display: none“样式的div,当我单击一个按钮时,我想删除那个类,我的JS工作一秒钟,我的意思是,我看到div之后,它又消失了。我把代码和代码链接放在这里。
<div class="container">
<div class="col-4 offset-4 text-center">
<h2>My to-do list</h2>
</div>
</div>
<div class="container" id="signin-form">
<div class="col-6 offset-3 align-self-center mt-2">
<h3 class="text-center">Sign in form</h3>
<form>
<div class="mb-3">
<label for="inputEmail" class="form-label">Email address</label>
<input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="inputPwd" class="form-label">Password</label>
<input type="password" class="form-control" id="inputPwd">
</div>
<div class="row mt-4" style="text-align: center;">
<div class="col-6">
<button id="login" class="btn btn-outline-primary">Login</button>
</div>
<div class="col-6">
<button id="signUp" class="btn btn-outline-success">Sign up</button>
</div>
</div>
<p class="mt-4 mb-4 small">If you already have an account please fill in the form and press "Login" otherwise press "Sign up"</p>
</form>
</div>
</div>
<div class="container noShow" id="register-form">
<div class="col-6 offset-3 align-self-center mt-2">
<h3 class="text-center ">Form for new user's registration</h3>
<form>
<div class="mb-3">
<label for="name " class="form-label ">Name (*)</label>
<input type="text " class="form-control " id="newName" required>
</div>
<div class="mb-3">
<label for="surname " class="form-label ">Surname</label>
<input type="text " class="form-control " id="newSurname">
</div>
<div class="mb-3">
<label for="inputEmail " class="form-label ">Email address (*)</label>
<input type="email " class="form-control " id="newEmail" aria-describedby="emailHelp " required>
</div>
<div class="mb-3">
<label for="inputPwd " class="form-label ">Password (*)</label>
<input type="text " class="form-control " id="newPwd" required>
</div>
<div class="row mt-4" style="text-align: center;">
<div class="col-4 offset-4 ">
<button type="submit " id="save" class="btn btn-outline-success ">Save</button>
</div>
</div>
<p class="mt-4 mb-4 small ">(*) Field are required</p>
</form>
</div>
</div>https://codepen.io/dome68/pen/wWLzpE
谢谢。
发布于 2021-03-21 21:10:48
删除类的步骤确实有效。这就是为什么你看到它起作用了一秒钟。
问题是按钮稍后提交表单,这就是为什么您再次看到它消失的原因。
如果未指定属性,则submit是与<form>关联的<button>的type的默认值。
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
要解决这个问题,给您的“注册”按钮分配一个type="button"属性,这使得它成为一个不提交表单的普通按钮。
<button type="button" id="signUp" class="btn btn-outline-success">Sign up</button>发布于 2021-03-21 20:43:44
将e.preventDefault()添加到事件处理程序以防止重新加载页面post form提交,如下所示:
function signUpFn(e) {
e.preventDefault();
document.getElementById("register-form").classList.remove("noShow");
document.getElementById("signin-form").classList.add("noShow");
}https://stackoverflow.com/questions/66737252
复制相似问题