2015-01-06 97 views
0

我想創建一個項目列表,其中的項目是基於按下按鈕來選擇的。然後他們在一個帶有刪除按鈕的表格(list-table)中出現。出於某種原因,我無法獲得與刪除按鈕關聯的點擊功能。點擊按鈕後,它應該將「作品」記錄到控制檯,但沒有任何反應。任何幫助/提示,​​表示讚賞!謝謝!需要幫助jquery點擊功能

$('.btn-primary').click(function(event) { 
    var foodItem = $(this).text(); 
    foodItem = foodItem.replace(/\s+/g, ''); 
    if ($(this).hasClass('active') == true){ 
     $(this).removeClass('active'); 
     $('#' + foodItem).remove(); 
     var itemIndex = groceryListArray.indexOf(foodItem) 
     groceryListArray.splice(itemIndex,1) 
    } 
    else{ 
     $(this).addClass('active'); 
     var newRow = '<tr id = ' + foodItem +'><td id="col-md-1"></td><td>' + foodItem + '</td><td class="remove"><div class="btn remove">Remove?</div></td></tr>'; 
     $(newRow).appendTo($('#list-table')); 
     groceryListArray.push(foodItem) 
    } 
}); 
//When an item is removed from the table via the remove? button 
$('.remove').click(function() { 
    console.log("works"); 
}); 
+2

這是因爲,在此之前還有一件禮物刪除按鈕,刪除按鈕的事件處理程序的約束,和'$(「刪除」)'只得到存在於DOM元素在它跑了,還不是時候元素稍後添加,因此您需要委派事件處理程序。 – adeneo

+0

[**瞭解事件代理**](http://learn.jquery.com/events/event-delegation/) – adeneo

+0

查看'.on'而不是點擊。像'$(document).on('click','.remove',function(){...});'會起作用。 http://api.jquery.com/on/ –

回答

0

刪除理由不工作是因爲你正在連接的點擊處理程序$('.remove')但Remove按鈕還不存在。點擊您的$('.btn-primary)對象後,即會創建刪除按鈕。

使用刪除按鈕作爲選擇器,將點擊處理程序附加到表中(假設它已存在),該處理程序將包含食品項目行。

$('table').on('click', '.remove', function() { 
    console.log("works"); 
});