如何用jQuery实现用户在最后一个section输入时自动复制新增模块
实现方案
直接对应你的三个疑问给出可运行解法:
- 复制section节点:使用jQuery的
clone()方法克隆现有节点即可,克隆后清空输入内容作为新的空白模块 - 生成唯一name属性:每次新增前先获取当前section的总数量,新的索引值为总数量+1,通过正则替换克隆节点中所有输入、选择框name属性的序号即可
- 避免多余空白section:仅监听最后一个section内输入框的输入事件,新增后新的空白section会自动成为最后一个监听对象,永远保证末尾只有1个空白模块
另外用input事件代替你原来用的change事件,用户开始输入就触发,不需要等失去焦点,更符合你的需求,完整代码如下,直接替换你现有JS部分即可:
// 事件委托绑定,兼容所有动态生成的section $('.attachments').on('input', 'section:last-child input', function() { const lastSection = $('.attachments section:last-child'); // 仅当最后一个section的标题有内容时才新增,避免误触发 if (lastSection.find('input[name$="[title]"]').val().trim() === '') return; // 克隆节点并清空内容 const newSection = lastSection.clone(); newSection.find('input, select').val(''); // 生成唯一name属性 const newIndex = $('.attachments section').length + 1; newSection.find('input, select').each(function() { const originName = $(this).attr('name'); const newName = originName.replace(/attach\[\d+\]/, `attach[${newIndex}]`); $(this).attr('name', newName); }); // 追加到容器末尾 $('.attachments').append(newSection); });
内容的提问来源于stack exchange,提问作者Mathew
相关产品推荐
相关产品推荐

