这是我的JQuery(来自我之前的问题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
?
答案 0 :(得分:4)
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();
},
您还可以使用ajax的context选项。
$.ajax({
//...
context: this,
success: function () {
$('#loader').hide();
$(this).closest('li').remove();
},
complete: function () {
$(this).parent('li').remove();
},