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

时间:2015-01-06 23:27:05

标签: javascript jquery html

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

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

1 个答案:

答案 0 :(得分:0)

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

使用移除按钮作为选择器,将单击处理程序附加到包含食物项行的表(假设它已存在)。

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