我第一次玩jQuery和AJAX,我似乎遇到了一个试图从数据库中删除条目的绊脚石。或者,更清楚的是,该项目已成功从数据库中删除,但是一旦删除它,我似乎无法选择要隐藏的正确元素。
以下是一些示例代码的样子(在这种情况下,我只是为了测试目的而尝试更改背景颜色:我将在生产环境中使用fadeOut或同等产品 - 后面会有更多解释):
//When link with class .deleter is clicked, get the parent element's id (which is also that element's id in the database)
$('.deleter').click(function() {
var recordToDelete = $(this).closest('ul').attr('id');
//Send the id to the PHP script, which returns 1 if successful and 0 if not
$.post("databasefuncs.php?func=delete", { postedMessage : recordToDelete },
function(result){
if(result == 1) {
//Change the background color of the parent UL to red if successful
$(this).closest('ul').css('background-color', 'red');
} else {
//Change the background color of the parent UL to blue if successful
$(this).closest('ul').css('background-color', 'blue');
}
});
});
为了澄清它在前端的外观,我的UL设置为:table-row,我的LI设置为显示:table-cell,我有一个包含所有的DIV,并设置为显示:表格。基本上,我每条记录都有一个UL,每条记录中每列有一个LI。
谢谢!
答案 0 :(得分:0)
您在AJAX回调中有不同的上下文。所以,$(this)指向另一个对象。我建议你应该在下面的例子中使用closure - variable“item”:
//When link with class .deleter is clicked, get the parent element's id (which is also that element's id in the database)
$('.deleter').click(function() {
var item = $(this).closest('ul');
var recordToDelete = item.attr('id');
//Send the id to the PHP script, which returns 1 if successful and 0 if not
$.post("databasefuncs.php?func=delete", { postedMessage : recordToDelete },
function(result){
if(result == 1) {
//Change the background color of the parent UL to red if successful
item.css('background-color', 'red');
} else {
//Change the background color of the parent UL to blue if successful
item.css('background-color', 'blue');
}
});
});