gpt4 book ai didi

使用ajax的jquery选择器

转载 作者:行者123 更新时间:2023-12-01 02:43:05 25 4
gpt4 key购买 nike

我有一个简单的.ajax点击事件触发的函数。该函数触发成功,我很难删除最近的 <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不再相关?我没有收到任何错误。有人可以识别我的错误吗?

最佳答案

ajax 成功回调中的

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')

关于使用ajax的jquery选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20253016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com