【问题标题】:jQuery Ajax callback doesn't recognise $(this) object [duplicate]jQuery Ajax 回调无法识别 $(this) 对象 [重复]
【发布时间】:2015-06-07 06:26:21
【问题描述】:

它是我的代码

$(".library-fields-container div.field-content img").click(function(){
    var nid = getImageNodeID($(this).siblings(".image-span").text());
    $.ajax({
        url: Drupal.settings.basePath + 'views/ajax',
        type: 'POST',
        dataType: 'json',
        data: 'view_name=fehrest&view_display_id=block_1&view_args='+nid,
        success: function(response) {
            var output = response[1].data;
            alert(output);  
            $(this).hide();
        },
        error: function(data) {
            alert('An error occured!');
        }
      });
});  

我确定output 变量打印了一些内容并且它不是空的,因为警报函数会显示它的内容。

问题是它没有隐藏 $(this) 而当我放的时候

$(this).hide();

在 Ajax 调用之前的单击事件开始时,它会隐藏图像。

$(this) 对象的 Ajax 回调函数是什么?

【问题讨论】:

标签: javascript jquery ajax callback this


【解决方案1】:

在这种情况下 - this 不是一个元素。 在 ajax 调用 this 之前保存到 self 变量。喜欢

var self = this;
$.ajax({
    ...
    success: function(response) {
        var output = response[1].data;
        alert(output);  
        $(self).hide();
    }
});

【讨论】:

    【解决方案2】:
    $(".library-fields-container div.field-content img").click(function(){
    var target = $(this);
    var nid = getImageNodeID($(this).siblings(".image-span").text());
    $.ajax({
        url: Drupal.settings.basePath + 'views/ajax',
        type: 'POST',
        dataType: 'json',
        data: 'view_name=fehrest&view_display_id=block_1&view_args='+nid,
        success: function(response) {
            var output = response[1].data;
            alert(output);  
            target.hide();
        },
        error: function(data) {
            alert('An error occured!');
        }
      });
    }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      相关资源
      最近更新 更多