我的代码遍历查询结果并将它们全部放在一个列表中供用户查看。如何添加删除按钮以删除列表项中指定的对象?目前,所有按钮仅删除最后一个结果。
query.exists("serviceName");
query.find({
success: function(results) {
//clears current list
(function($) {
$("#service-table li").remove();
})(jQuery);
//retrieves new up-to-date list
for (var i = 0; i < results.length; i++) {
var object = results[i];
//Inserts each retrieved serviceName as a list item into the HTML
(function($) {
$('#service-table').append('<li class="list-group-item"><span class="badge" id="delete">DELETE</span><a href="#" id="listItemService">' + object.get('serviceName') + '</a></li>');
})(jQuery);
//Supposed to delete the relevant object but all delete buttons delete last list item
(function($) {
$('#delete').on('click', function() {
object.destroy({
success: function(object) {},
error: function(object, error) {}
})
});
})(jQuery);
}
},
error: function(error) {}
});
这是列表的一个例子。
答案 0 :(得分:1)
以下是一些问题:
一种解决方案是使用data-attributes让每个删除按钮引用结果中的相应项目。您可以为每个删除按钮分配 data-id 属性,并将其值设置为相应结果项的索引。然后,在将“click”事件绑定到删除按钮时,使用 event.target 获取被点击元素的 data-id 值并销毁相应的对象。
for (var i = 0; i < results.length; i++) {
// Inserts each retrieved serviceName as a list item into the HTML
// Assigns i as the data-id value for each delete button
(function($) {
$('#service-table').append('<li class="list-group-item"><span class="badge delete" data-id=i>DELETE</span><a href="#" id="listItemService">' + object.get('serviceName') + '</a></li>');
})(jQuery);
(function($) {
$('.delete').on('click', function(event) {
// Gets the value of the clicked delete button's data-id attribute
var dataID = $(event.target).attr('data-id');
// Finds the results item whose index is dataID
var object = results[dataID];
object.destroy({
success: function(object) {},
error: function(object, error) {}
})
});
})(jQuery);
},