簡體   English   中英

如何將jQuery的這個對象傳遞給內部成功函數?

[英]How to pass this object of jquery into inner success function?

下面是我的代碼。 我想基於ajax回調更改每個mainimage src。

jQuery('.xxx img[src*="mainimage"]').each(function() {
  vobj = $(this);
  var inmainurl = 'https://xxx.kki/api/oembed.json?url=' + $(this).attr('src');
  $.ajax({
    url: inmainurl,
    dataType: 'json',
    success: function(result) {
      $(this).attr('src', result.thumbnail_url); //this is not working.
    }
  });
});

下面不起作用

success: function (result) {                           
    $(this).attr('src',result.thumbnail_url);//this is not working.
}

如何實現的?

如果將內部$(this).attr更改為vobj.attr是否可以解決您的問題?

看到vobj是您定義的變量。

代替

$(this).attr('src', result.thumbnail_url);

vobj.attr('src', result.thumbnail_url);

this是函數上下文,兩個函數都不同,但是ajax回調可以訪問vobj變量。

您需要在循環中使用閉包,否則vobj $.ajax調用后, vobj變量將變為下一個元素。 您還需要在success處理程序中使用vobj變量。 嘗試這個:

jQuery('.xxx img[src*="mainimage"]').each(function() {
    (function($el) {
        $.ajax({
            url: 'https://xxx.kki/api/oembed.json?url=' + $el.attr('src');,
            dataType: 'json',
            success: function(result) {
                $el.attr('src', result.thumbnail_url);
             }
        });
    })($(this));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM