2015-04-28 10 views
1

我正在開發一個需要使用+/- (加號,減號)按鈕動態添加字段的表單。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

任何幫助或提示可以理解的:)

歐麥

+1

對於動態元素,現有的父元素上使用事件傳播。 jQuery(document).on('click','.jfs_btn',function(){ – SSA

+0

你是什麼意思的事件傳播? – Omer

+1

https://learn.jquery.com/events/event-delegation/ – SSA

回答

5

DEMO:https://jsfiddle.net/64sfpf5j/1/

刪除按鈕是動態創建的,所以應該使用.on()方法是這樣的:

jQuery('body').on('click', '.jfs_remove', function() { 

    $(this).closest('div').remove(); 
}); 
+0

我用過.on(),但它不適合我... '$('。jfs_remove')。on('click',function(){ alert(' test'); })' – Omer

+0

爲什麼你使用**「body」**作爲選擇器? – Omer

+1

@Omer因爲'body'包含帶有'.jfs_remove'類的動態元素,它可以是任何非動態元素,它包含具有'.jfs_remove'類 – renakre