我正在开发一个表单,需要使用+/-(加号、减号)按钮动态添加字段。
代码完美地添加了字段,但是当我尝试删除它时,它不起作用。
这是我的代码:
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
任何帮助或提示将不胜感激:)
奥马尔
最佳答案
演示:https://jsfiddle.net/64sfpf5j/1/
删除按钮是动态创建的,因此您应该使用 .on()
方法,如下所示:
jQuery('body').on('click', '.jfs_remove', function () {
$(this).closest('div').remove();
});
关于jQuery 检测 jQuery 本身添加的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29923579/