在 jquery 点击功能方面需要帮助

Need help in jquery click function

我正在尝试创建一个项目列表,其中的项目是根据按下按钮来选择的。然后它们会出现在带有删除按钮的 table (list-table) 中。出于某种原因,我无法使与删除按钮关联的点击功能起作用。单击该按钮时,它应该将 "works" 记录到控制台,但没有任何反应。任何 help/tips 都表示赞赏!谢谢!

$('.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");
});

删除不起作用的原因是您将点击处理程序附加到 $('.remove'),但删除按钮尚不存在。单击 $('.btn-primary) 对象后,将创建删除按钮。

将点击处理程序附加到将包含您的食品行的 table(假设它已经存在),使用您的删除按钮作为选择器。

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