我有一个简单的.ajax
函数,它在click事件中触发。该功能成功触发,我很难删除最近的<tr>
标签以确认删除。
$('.delete_item').click(function () {
if (confirm('Delete this location?')) {
$.ajax({
type: "POST",
url: "/Admin/Location/Delete",
data: "{id: '" + $(this).attr('id') + "' }",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (msg) {
if (!msg) {
alert('There was an error deleting the location.');
return;
}
else {
$(this).closest('tr').css('background-color', '#df8f8f').delay(800).fadeOut('slow');
}
},
error: function (msg) {
alert('error in ajax call');
},
});
}
return false;
});
这是标记
<tr class="class">
<td style="width:300px;">Rosana Square</td>
<td>24 Hours</td>
<td style="width:300px;">8555 Monrovia</td>
<td style="width:300px;">http://www.website.com</td>
<td style="width:50px; text-align:center;"><a href="/Admin/Location/Edit/13"><span class="glyphicon glyphicon-edit"></span></a></td>
<td style="width: 50px; text-align: center;"><a href="#_" id="13" class="delete_item"><span class="glyphicon glyphicon-trash"></span></a></td>
</tr>
这个ajax的内部this
不再相关?我没有收到任何错误。有人可以识别我的错误吗?
答案 0 :(得分:5)
this
是你的问题,因为它没有引用元素,而是jqXhr对象。尝试在ajax设置或缓存上下文中设置上下文。
$('.delete_item').click(function () {
if (confirm('Delete this location?')) {
$.ajax({
type: "POST",
url: "/Admin/Location/Delete",
data: "{id: '" + this.id + "' }",
contentType: "application/json; charset=utf-8",
context: this, //<--- Set the context
dataType: "text",
success: function (msg) {
if (!msg) {
alert('There was an error deleting the location.');
return;
}
else {
$(this).closest('tr').css('background-color', '#df8f8f').delay(800).fadeOut('slow');
}
},
error: function (msg) {
alert('error in ajax call');
},
});
}
return false;
});
或者
$('.delete_item').click(function () {
if (confirm('Delete this location?')) {
var self = this; //Set it here
....
....
success: function (msg) {
if (!msg) {
alert('There was an error deleting the location.');
return;
}
else {
$(self).closest('tr').css('background-color', '#df8f8f').delay(800).fadeOut('slow');
}
另外在旁注中,您可以使用this.id
代替$(this).attr('id')
答案 1 :(得分:1)
始终可以为this
var that = $(this);
$.ajax({
..
..
success: function() {
that.closest('tr').css(