我正在開發一個需要使用+/- (加號,減號)按鈕動態添加字段的表單。jQuery檢測由jQuery本身添加的類
該代碼完美添加字段,但是當我嘗試刪除它時,它不起作用。
這裏是我的代碼:
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小提琴也代碼:My Fiddle Link
任何幫助或提示可以理解的:)
歐麥
對於動態元素,現有的父元素上使用事件傳播。 jQuery(document).on('click','.jfs_btn',function(){ – SSA
你是什麼意思的事件傳播? – Omer
https://learn.jquery.com/events/event-delegation/ – SSA