簡體   English   中英

我可以將$(this)傳遞給.getJSON回調函數嗎?任何解決方法?

[英]Can I pass $(this) to the .getJSON callback function? any workaround?

我試圖在每個li上獲取rel的值並將其傳遞給.getJSON函數。 然后我想將回調中的thumbnail_url值添加到li后代的image標簽中。 我的問題是如何將$(this)對象傳遞給回調函數。 似乎$(this)為null。

$('ul.sample li').each(function () {

        var url = 'http://sampleurl/api/url?' + $(this).attr('rel');

        $.getJSON(url, function (data){
            $(this).find('img').attr('src') = data.thumbnail_url;
    })
});

HTML:

<ul class="sample">
   <li rel="value1">
       <img src="">
   </li>
   <li rel="value2">
       <img src="">
   </li>
</ul>

只需將它分配給回調之外(就像我設置self )然后使用內部回調(通過引用你設置的變量):

$('ul.sample li').each(function () {

    var self = $(this); // using self to store $(this)
    var url = 'http://sampleurl/api/url?' + self.attr('rel');

    $.getJSON(url, function (data) {
        // now retrieving self - it is accessible from the callback
        self.find('img').attr('src') = data.thumbnail_url;
    });

});

其原因是因為this是在回調不同.each()不是在回調$.getJSON()

如果使用$.ajax而不是$.getJSON ,則可以使用context選項:

$('ul.sample li').each(function () {
    var url = 'http://sampleurl/api/url?' + $(this).attr('rel');
    $.ajax({
        url : url,
        dataType : 'json',
        context : this,
        complete : function (data) {
            // 'this' will be what you passed as context 
            $(this).find('img').attr('src') = data.thumbnail_url;
        }
    });
});

暫無
暫無

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

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