使用jQuery实现带动态子输入项的输入组 新追加组无法动态添加字段
问题原因与修复方案
你的代码核心问题有三点:
- 动态插入的元素没有绑定事件:初始化时绑定
.add_button点击事件只会作用于页面加载时就存在的按钮,后续新增组里的添加按钮没有绑定对应事件,所以点击无效。 - 移除组的选择器逻辑错误:
closest('group_wrapper')写法错误,缺少类选择器的.标识,且DOM结构中删除按钮和表格是同级关系,无法通过父级查找匹配。 - 全局字段计数不合理:所有分组共用同一个全局x计数,多组同时操作时会出现计数混乱、无法正常添加字段的问题。
修复后完整JS代码
var max_group = 5; var group_wrapper = $('.group_wrapper'); var max_field = 10; var html_group = '' + '<a href="javascript:void(0);" class="remove_group btn btn-sm btn-danger pull-right"><i class="fa fa-minus"></i> remove group</a>'+ '<table id="itemTable" class="table">'+ '<thead>'+ '<tr>'+ '<th>Item Name</th>'+ '<th>Item Description</th>'+ '<th>Action</th>'+ '</tr>'+ '</thead>'+ '<tbody class="field_wrapper">'+ '<tr class="item-group">'+ '<td><input type="text" class="form-control" placeholder="Group name"></td>'+ '</tr>'+ '<tr class="item">'+ '<td><input type="text" class="form-control" placeholder="Item name"></td>'+ '<td><input type="text"class="form-control" placeholder="Item Description"></td>'+ '<td><a href="javascript:void(0);" class="add_button btn btn-sm btn-primary" title="Add field"><i class="fa fa-plus"></i></a></td>'+ '</tr>'+ '</tbody>'+ '</table>'; var html_fields = '' + '<tr class="item">' + '<td> <div class="form-group mb-0"> <input type="text" class="form-control" placeholder="Item name"> </div> </td> ' + '<td> <div class="form-group mb-0"> <input type="text" class="form-control" placeholder="Item Description"> </div> </td> ' + '<td> <a href="javascript:void(0);" class="remove_button btn btn-sm btn-danger"><i class="fa fa-minus"></i></a> </td>' + '</tr>'; var y = 1; // 新增组事件 $('.add_group').click(function(){ if( y < max_group){ y++; group_wrapper.append(html_group); } }); // 移除组事件 group_wrapper.on('click', '.remove_group', function(e){ e.preventDefault(); // 先删除同级的表格,再删除按钮本身 $(this).next('table').remove(); $(this).remove(); y--; }); // 新增字段事件(改为事件委托,适配动态插入的按钮) group_wrapper.on('click', '.add_button', function(){ // 取当前组内的字段数,避免全局计数混乱 var currentWrapper = $(this).closest('.field_wrapper'); var currentCount = currentWrapper.find('.item').length; if(currentCount < max_field){ currentWrapper.append(html_fields); } }); // 移除字段事件 group_wrapper.on('click', '.remove_button', function(e){ e.preventDefault(); $(this).closest('tr').remove(); });
修改说明
- 把
.add_button的点击事件改为绑定到固定存在的group_wrapper父级容器上,所有动态插入的添加按钮都能触发事件。 - 修正了删除组的逻辑,直接找到删除按钮同级的表格元素删除,再删除按钮本身。
- 去掉了全局的x计数,改为每次点击添加按钮时统计当前组内的字段数量,多组操作互不干扰。

内容的提问来源于stack exchange,提问作者Firefog
相关产品推荐
相关产品推荐

