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");
});
這是因爲,在此之前還有一件禮物刪除按鈕,刪除按鈕的事件處理程序的約束,和'$(「刪除」)'只得到存在於DOM元素在它跑了,還不是時候元素稍後添加,因此您需要委派事件處理程序。 – adeneo
[**瞭解事件代理**](http://learn.jquery.com/events/event-delegation/) – adeneo
查看'.on'而不是點擊。像'$(document).on('click','.remove',function(){...});'會起作用。 http://api.jquery.com/on/ –