繁体   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