这是我的 JQuery(来 self 之前的问题 Invoke ColdFusion method with on click in JQuery)
$("#FileUploader").on('click', '.DeleteFileUpload', function (e) {
e.preventDefault();
$(this).text('Deleting...'); // changes link text to say its deleting
$.ajax({
type: 'post',
url: 'mycfc.cfc?method=deletefile',
data: {
Filename: $(this).attr('href') // name of file to delete is in the href
},
dataType: "json",
beforeSend: function () {
$('#loader').show(); // show a loading spinner
},
success: function () {
$('#loader').hide(); // on succcess hide the spinner
$(this).closest('li').remove(); // should remove the closest li which displays the file name but this does not work
},
complete: function () {
$(this).parent('li').remove(); // should remove the parent li which displays the file name but this does not work
},
error: function (result) {
alert("An error has occured.");
}
});
});
所以我尝试删除最近的 li
和父 li
(两者都应该做同样的事情),但都不起作用。但是如果我将这行代码放在 Ajax() 函数之前,那么它的工作原理如下:
$("#FileUploader").on('click', '.DeleteFileUpload', function (e) {
e.preventDefault();
$(this).parent('li').remove(); // this works and the li is removed!
.........
谁能帮我解决为什么我无法删除成功/完成区域中的 li
吗?
最佳答案
ajax中的this
并不在你想象的上下文中。
试试这个:
$("#FileUploader").on('click', '.DeleteFileUpload', function (e) {
e.preventDefault();
var self = $(this);
//......... later on inside the ajax call
success: function () {
$('#loader').hide();
self.closest('li').remove();
},
complete: function () {
self.parent('li').remove();
},
您还可以使用context ajax 选项。
$.ajax({
//...
context: this,
success: function () {
$('#loader').hide();
$(this).closest('li').remove();
},
complete: function () {
$(this).parent('li').remove();
},
关于jquery - 无法在成功或完成时删除父级 <li>,但可以在此之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21075378/