模态框表单中e.preventDefault()失效,求技术解决方案
解决模态框表单e.preventDefault()失效与required验证问题
核心问题出在事件绑定的对象错了:你把submit事件绑到了按钮上,但submit事件是表单元素的专属事件,按钮不会触发它,所以你的监听代码根本没跑起来,e.preventDefault()自然无效。而绑click事件时,浏览器不会触发原生的required验证流程,导致验证失效。
修正步骤
1. 给表单绑定submit事件
把事件监听从按钮移到<form>元素上,这样既能触发原生验证,又能阻止默认提交:
// 先获取表单元素 const bookForm = document.querySelector('.bookTag'); // 给表单绑定submit事件 bookForm.addEventListener('submit', function(e) { // 先阻止默认提交行为,这一步要放在最前面 e.preventDefault(); // 获取所有表单输入值 const title = document.getElementById('title'); const author = document.getElementById('author'); const pages = document.getElementById('pages'); const readCheckbox = document.getElementById('read'); // 执行你的书籍添加逻辑 myLibrary[x] = new book(title.value, author.value, pages.value, readCheckbox.checked); addbook(title.value, author.value, pages.value, x, readCheckbox.checked); x++; // 清空表单 title.value = author.value = pages.value = ""; readCheckbox.checked = false; // 关闭模态框 modal.style.display = "none"; });
2. 修正复选框状态获取
原来用read.value是错的,复选框的选中状态要拿checked属性,它返回布尔值true/false,而value默认是固定的on,没有实际意义。
3. 为啥原来的写法不行?
- 绑按钮的click事件:点击submit按钮时,
click事件会先触发,但浏览器的原生表单验证是在表单的submit事件阶段执行的,所以绑click会跳过验证流程,required规则失效。 - 绑按钮的submit事件:
<button>元素本身不存在submit事件,这个监听完全不会被触发,你的代码逻辑根本没执行,自然谈不到阻止默认行为。
修正后的完整JS参考
// 模态框相关逻辑 var modal = document.getElementById("myModal"); var btn = document.getElementById("myBtn"); var span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display = "block"; } span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } // 表单提交逻辑(修正后) const bookForm = document.querySelector('.bookTag'); bookForm.addEventListener('submit', function(e) { e.preventDefault(); const title = document.getElementById('title'); const author = document.getElementById('author'); const pages = document.getElementById('pages'); const readCheckbox = document.getElementById('read'); // 假设myLibrary、book构造函数、addbook函数已提前定义 myLibrary[x] = new book(title.value, author.value, pages.value, readCheckbox.checked); addbook(title.value, author.value, pages.value, x, readCheckbox.checked); x++; title.value = author.value = pages.value = ""; readCheckbox.checked = false; modal.style.display = "none"; });
内容的提问来源于stack exchange,提问作者Kukii
相关产品推荐
相关产品推荐

