基于jQuery的发票产品动态增删、序号维护与金额计算功能异常
发票动态产品项功能的问题修正方案
原代码的核心逻辑缺陷
- 删除逻辑硬编码匹配全局
divCount对应的类名,无论点击哪个删除按钮,都只会尝试删除类名为.item-wrapper-${divCount}的块,和当前点击按钮所属的块无关联,导致删除任意前置位置的块时逻辑失效 - 依赖全局自增计数器
divCount生成块的类名和显示编号,删除前置块时计数不会同步调整,后续新增块时会和现存块的类名、编号重复,连带取值、计算全部错位 - 所有动态生成的表单元素设置了重复的全局id(如
productName、sellPrice、quantity),违反HTML id全局唯一的规范,jQuery选择器匹配时永远只会取页面中第一个同id的元素,导致值串块、取值错误 - 每次新增块时都重复绑定
change事件,没有和当前块的作用域绑定,选择不同块的产品时,填充的值会固定写到最早创建的块里
正确实现的核心思路
- 不再依赖全局计数器作为块的身份标识,给所有产品块加通用的
product-item类,操作元素时统一从当前触发事件的节点出发,用closest()找到对应的父块,不依赖全局变量做匹配 - 每次增删块完成后,统一遍历所有现存的产品块,按实际DOM顺序重新生成连续的显示编号,从机制上避免编号不连续的问题
- 动态生成的表单元素全部用类做选择器,不使用重复id,从根本上避免选择器匹配错误
- 所有动态元素的事件统一委托给静态父容器绑定,不重复绑定事件,避免事件叠加
修正后的完整实现代码
基础HTML结构
<div class="productDiv"></div> <div class="mt-3 text-center"> <button class="btn profile-button" style="color: white" type="button" id="btnAddtoList">পণ্য যোগ করুন</button> </div> <div class="mt-3 text-center"> <button class="btn profile-button" style="color: white" type="button" id="subTotal">সাব টোটাল</button> </div> <div class="subTotalDiv"></div>
核心JS逻辑
$(function() { // 新增产品块 $('#btnAddtoList').on('click', function() { const newItem = $(` <div class="product-item"> <div class="container rounded bg-white mt-3 mb-3"> <div class="row"> <div class="col-md-12"> <div class="row mt-3"> <span><strong>পণ্যের বিবরণ #<span class="item-index"></span></strong></span> </div> <div class="row mt-1 text-center"> <select class="product_option form-control"> <option disabled selected> -- পণ্য পছন্দ করুন (পণ্যের নাম | বিক্রয় মূল্য | অ্যাভেলেবল আছে) -- </option> </select> </div> <div class="row mt-3"> <label class="labels" style="font-size: 16px">পণ্যের নাম</label> <input type="text" class="form-control product-name"> </div> <div class="row mt-3"> <label class="labels" style="font-size: 16px">বিক্রয় মূল্য</label> <input type="number" class="form-control sell-price"> </div> <div class="row mt-3"> <label class="labels" style="font-size: 16px">পণ্য মজুদ আছে </label> <input type="text" class="form-control stock-amount"> </div> <div class="row mt-3"> <label class="labels" style="font-size: 16px">পরিমাণ</label> <input type="number" class="form-control quantity_pro"> </div> <div class="mt-3 d-flex flex-column align-items-center text-center"> <button class="btn btn-danger deleteItem" type="button">মুছুন</button> </div> </div> </div> </div> </div> `); $('.productDiv').append(newItem); // 初始化Select2 newItem.find(".product_option").select2({ theme: "classic" }); // 加载云端产品选项,和当前块绑定 firebase.auth().onAuthStateChanged(function(user) { if (user) { const user_id = user.uid; firebase.database().ref('Products/').child(user_id).once('value') .then(function(snapshot) { snapshot.forEach(function(childSnapshot) { const product_name = childSnapshot.child("product_name").val(); const selling_price = childSnapshot.child("selling_price").val(); const amount = childSnapshot.child("product_quantity").val(); const optionText = `${product_name} | ${selling_price} | ${amount}`; newItem.find(".product_option").append(`<option>${optionText}</option>`); }); }) } else { window.location.href = "{% url 'login' %}"; } }); // 新增完成后重排序号 updateItemIndex(); }); // 删除产品块 $(document).on("click", ".deleteItem", function() { $(this).closest(".product-item").remove(); // 删除完成后重排序号 updateItemIndex(); }); // 统一更新产品块序号 function updateItemIndex() { $('.product-item').each(function(index) { $(this).find('.item-index').text(index + 1); }); } // 产品选择联动填充 $(document).on("change", ".product_option", function() { const currentItem = $(this).closest(".product-item"); const valArr = $(this).find("option:selected").text().split(" | "); currentItem.find('.product-name').val(valArr[0]); currentItem.find('.sell-price').val(valArr[1]); currentItem.find('.stock-amount').val(valArr[2]); }); // 小计计算 $("#subTotal").on('click', function() { let subTotalAmount = 0; let stockValid = true; // 遍历所有产品块计算 $('.product-item').each(function() { const currentItem = $(this); const price = parseFloat(currentItem.find('.sell-price').val()) || 0; const stock = parseFloat(currentItem.find('.stock-amount').val()) || 0; const qty = parseFloat(currentItem.find('.quantity_pro').val()) || 0; if (qty > stock) stockValid = false; subTotalAmount += price * qty; }); if (!stockValid) { alert("পর্যাপ্ত পরিমান পণ্য নেই ।"); return; } // 生成小计模块 const subDiv = $(` <div class="item-wrapper"> <div class="container rounded bg-white mt-3 mb-3"> <div class="row"> <div class="col-md-12"> <div class="row mt-3"> <span class="col-md-12">সাব টোটালঃ ${subTotalAmount}</span> </div> <div class="row mt-3"> <label class="labels" style="font-size: 16px">ডিসকাউন্ট(%)</label> <input type="text" class="form-control discount-input"> </div> <div class="row mt-3"> <label class="labels" style="font-size: 16px">ভ্যাট(%)</label> <input type="text" class="form-control vat-input"> </div> <div class="row mt-3"> <span class="col-md-12"><strong>মোটঃ</strong></span> </div> <div class="mt-3 d-flex flex-column align-items-center text-center"> <button class="btn btn-info" type="button">মোট</button> </div> </div> </div> </div> </div> `); $('.subTotalDiv').html(subDiv); }); })
关键实现细节说明
- 所有动态生成的元素禁止使用重复id,这是动态DOM开发最容易触发的bug,重复id会直接导致选择器匹配错误
- 删除操作永远从当前触发事件的节点出发,用
closest()定位目标块,不要依赖全局计数做匹配,避免因为计数和实际DOM结构不一致导致操作错位 - 只要发生增删块的操作,就调用一次
updateItemIndex()重排序号,不需要手动维护全局计数,从机制上保证编号永远连续 - 所有动态元素的事件统一委托给静态父容器绑定,不要在每次新增DOM时重复绑定事件,避免事件叠加、值串块的问题
页面编号重复问题的实际表现可参考对应截图:
内容的提问来源于stack exchange,提问作者Md. Ashiqur Rahaman Dipto
相关产品推荐
相关产品推荐


