jquery - 无法在成功或完成时删除父级 <li>,但可以在此之前

标签 jquery

这是我的 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/

相关文章:

javascript - 设置overflow-y滚动条的样式

javascript - 文件上传验证器 - jQuery/Javascript

jquery - 显示:none not working in IE 9

jquery - 在 asp.net 中下载文件后完成事件触发

jquery - 为什么我的页面比 <html> 元素高?

javascript - jQuery .val() 不会生成 'change'

javascript - 超出最大调用堆栈大小避免出现这种情况

javascript - 是否可以使用 JavaScript 获取 SVG 图像的 XML?

javascript - 访问 JavaScript 数组值

jquery - 将图片插入 2 列文本