代码之家  ›  专栏  ›  技术社区  ›  oshirowanen

jqueryajax成功问题

  •  3
  • oshirowanen  · 技术社区  · 15 年前

    $(".ui-delete").click(function() {
    
        $.ajax({
            url: 'delete.aspx',
            type: 'POST',
            data: { strWidgetID:$(this).parents(".widget").attr("id") },
            error: function() { alert('Error'); },
            success: function() { alert('Success'); }
        });
    
    
        $(this).parents(".widget:first").remove();
    });
    

    但是下面这个“更合适”的查询不能通过删除html实体来工作?

    $(".ui-delete").click(function() {
    
        $.ajax({
            url: 'delete.aspx',
            type: 'POST',
            data: { strWidgetID:$(this).parents(".widget").attr("id") },
            error: function() { alert('Error'); },
            success: function() {
                alert('Success');
                $(this).parents(".widget:first").remove();
            }
        });
    
    });
    

    有什么想法吗?

    2 回复  |  直到 15 年前
        1
  •  7
  •   Dave Ward    15 年前

    在成功处理程序中, this

    在$.ajax调用之前,您感兴趣的是:

    $(".ui-delete").click(function() {
      var that = this;
    
      $.ajax({
        // etc.
        success: function() {
          $(that).parents('.widget:first').remove();
        }
      });
    };
    
        2
  •  1
  •   chedine    15 年前

    根据上下文,$(this)引用不同的对象。查看此链接 What is this? 在第二个代码示例中,这是指ajax设置对象,而不是“ui delete”元素。