我正在开发一个需要使用+ / - (加号,减号)按钮动态添加字段的表单。
代码正在完美地添加字段,但是当我尝试删除它时,它无法正常工作。
这是我的代码:
HTML
<div class="jfs_product_detail_fields">
<span class="jfs_product_name"><input type="text" name="product name" placeholder="Product Name"></span>
<span class="jfs_product_id"><input type="text" name="product ID" placeholder="Product ID#"></span>
<span class="jfs_qty"><input type="text" name="Qty" placeholder="Quantity"></span>
<button class="jfs_btn">+</button>
<div class="jfs_clr"></div>
</div>
JQUERY
// making them unique
var num = 1;
// cloning
jQuery('.jfs_btn').on('click', function () {
if (jQuery(this).hasClass('jfs_remove')) {
alert('test');
} else {
var fields = '<div id="jfs_product_detail_fields"><span class="jfs_product_name"><input type="text" name="product_name_' + num + '" placeholder="Product Name"></span><span class="jfs_product_id"><input type="text" name="product_id_' + num + '" placeholder="Product ID#"></span><span class="jfs_qty"><input type="text" name="qty_' + num + '" placeholder="Quantity"></span><button class="jfs_btn jfs_remove">-</button><div class="jfs_clr"></div></div>';
num = num + 1;
jQuery('.jfs_product_detail_fields:first').before(fields);
}
});
以下是关于JS Fiddle的代码:My Fiddle Link
任何帮助或提示将不胜感激:)
欧麦
答案 0 :(得分:4)
DEMO:https://jsfiddle.net/64sfpf5j/1/
删除按钮是动态创建的,因此您应该使用.on()
方法,如下所示:
jQuery('body').on('click', '.jfs_remove', function () {
$(this).closest('div').remove();
});