使用e.preventDefault()阻止表单提交仍跳转页面问题求解
问题原因
- JS执行时机错误:你将
<script src="app.js"></script>放在了<head>标签内,浏览器解析到该标签时会立即加载执行JS代码,此时<body>内的表单元素还没有渲染到DOM树中,代码中使用的form变量无法获取到对应的DOM元素,导致submit事件监听器绑定失败,e.preventDefault()逻辑根本不会执行,因此点击提交按钮会触发默认的表单跳转行为。 - 缺失form元素获取逻辑:你提供的JS代码中没有编写获取form DOM元素的语句,
form变量本身是未定义的,也是事件绑定失败的直接原因之一。
解决方案
第一步:调整JS引入位置
将<script src="app.js"></script>从<head>移动到</body>闭合标签之前,确保所有DOM元素加载完成后再执行JS代码,修改后的HTML结构如下:
<head> <title>Grocery List</title> </head> <body> <h1>Grocery List</h1> <form action="/nowhere"> <label for="product">Enter A Product</label> <input type="text" id="product" name="product"> <label for="qty">Enter A Quantity</label> <input type="number" id="qty" name="qty"> <button>Submit</button> </form> <ul id="list"></ul> <!-- JS文件改到body末尾引入 --> <script src="app.js"></script> </body> </html>
额外说明:原HTML中两个label的for属性都写为item,和对应input的id不匹配,已同步修正,该问题不会影响表单提交逻辑,但会影响无障碍访问和点击label聚焦输入框的体验
第二步:补全JS代码
在JS开头添加form元素的获取逻辑,修改后的代码如下:
// 补全form元素获取语句 const form = document.querySelector('form'); const container = document.querySelector('#list'); form.addEventListener('submit',function(e){ e.preventDefault(); const getProduct = form.elements.product.value; const getQty = form.elements.qty.value; const newli = document.createElement('li'); newli.append(getQty); newli.append(` ${getProduct}`); container.append(newli); form.elements.product.value = ''; form.elements.qty.value = ''; })
内容的提问来源于stack exchange,提问作者Okta25
相关产品推荐
相关产品推荐

