表单内jQuery添加按钮异常:新增DIV一闪即消失求助
问题原因与解决办法
核心问题
放在<form>标签内的<button>默认是submit类型,点击后会触发表单提交动作,导致页面刷新——刚新增的.room元素会随着页面重置消失。把按钮移到form外就不会触发表单提交,所以功能正常。
两种快速修复方式
- 方式一:指定按钮类型
给#add按钮加上type="button",明确它是普通功能按钮,不会触发表单提交:
<button id="add" type="button">Add new div</button>
- 方式二:拦截默认提交行为
在点击事件里添加event.preventDefault(),阻止表单提交的默认动作:
$("#add").click(function(event) { event.preventDefault(); // 阻止表单提交刷新页面 div = document.createElement('div'); $(div).addClass("room").html("new Room Type"); $("#roomTypes").append(div); });
整合「添加/移除」功能的完整代码
结合你的需求,下面是修复了消失问题、同时实现移除功能的完整代码,还优化了表单提交时的数组参数传递:
<html> <header> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script> <script type="text/javascript"> $(function() { // 添加房型 $("#add").click(function(event) { event.preventDefault(); // 动态生成带移除按钮的房型模块 let roomDiv = $('<div class="room">').html(` Room Type: <input type="text" name="RoomType[]" value="New Room"><br> <button class="remove" type="button">移除</button> `); $("#roomTypes").append(roomDiv); }); // 移除房型(用事件委托处理动态生成的元素) $("#roomTypes").on('click', '.remove', function() { $(this).closest('.room').remove(); }); }); </script> <style> #container {border: 1px solid red; padding: 10px; width: 100%;} .inner {border: 1px solid green; margin: 10px; width: auto; height: 20px;} .room {margin: 10px 0; padding: 5px; border: 1px solid #ccc;} </style> </header> <body> <h1>Numbers Project</h1> <p>Version 0.1</p> <form> Hotel Name: <input type="text" name="Name" value="Roma Nord"><br> Hotel Stars: <input type="number" name="Stars" value="3"><br> <div id="roomTypes"> <div class="room"> Room Type: <input type="text" name="RoomType[]" value="Double"><br> <button class="remove" type="button">移除</button> </div> </div> <button id="add" type="button">Add new Room Type</button> Opening Date: <input type="date" name="OpenDate" value="2021-01-01"><br> Closing Date: <input type="date" name="CloseDate" value="2021-06-30"><br> <h3>Previous Year Data</h3> Rooms sold: <input type="number" name="RoomsSold" value="12000"><br> Arrivals Presences: <input type="number" name="ArrivalsPresences" value="15000"><br> Presences: <input type="number" name="Presences" value="23000"><br> <br><input type="submit" value="Submit"> </form> </body> </html>
注:把name="RoomType"改成name="RoomType[]",后端接收表单数据时能直接拿到所有房型的数组值。
内容的提问来源于stack exchange,提问作者Mauro Ghiglia
相关产品推荐
相关产品推荐

