$(this) 不适用于 Flickr Gallery

$(this) not working with Flickr Gallery

本文关键字:适用于 Flickr Gallery 不适用 this      更新时间:2023-09-26

请在此处查看我的代码笔:http://codepen.io/dsm/pen/ewEJb

此应用程序将显示两个Flickr画廊。我正在尝试将函数分离以完全独立于函数调用。但是,我目前可以让它工作的唯一方法是对行进行硬编码以包含div id '#flickr'。我尝试改用$(this),但似乎不合作。

有什么建议吗?

$('#flickr').append('<h2>'+photosetTitle+'</h2>');
$('#flickr').append(theHtml);

以上是有问题的代码行,可以在下面的代码中看到。

注意:此代码假定 jquery 已经加载。

(function($){
    $.fn.flickrSetGallery = function(callerSettings) { 
        var settings = $.extend(callerSettings); 
        var url = 'http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=';
        url += settings.apiKey;
        url += '&photoset_id=';
        url += settings.photosetID;
        url += '&format=json&jsoncallback=?';   
        $.getJSON(url, displayImages);
        function displayImages(data) {
            var photosetTitle = data.photoset.title;
            var photosetTag = photosetTitle.toLowerCase().trim().split(/'s+/).join
            var theHtml = "";
            $.each(data.photoset.photo, function(i,photo){
                var source = 'http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_s.jpg';
                theHtml+= '<li><a href="http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_b.jpg" data-lightbox="'+photosetTag+'">';
                theHtml+= '<img title="'+photo.title+'" src="'+source+'" alt="'+photo.title+'" />';
                theHtml+= '</a></li>';              
            });
            $('#flickr').append('<h2>'+photosetTitle+'</h2>');
            $('#flickr').append(theHtml);
        };
    };
})(jQuery);
$(document).ready(function() {
    $('#flickr').flickrSetGallery({
        apiKey: '2eabc9d4b3a1b7443b2900a729b8b4a8',
        photosetID: '72157616127960344'        
    });
    $('#flickr2').flickrSetGallery({
        apiKey: '403e03feaf4819a91a02f158a0504075',
        photosetID: '72157637557971086'    
    });
});

这是 HTML:

<div id="flickr" class="flickr-things">
</div>
<div id="flickr2" class="flickr-things">
</div>

尝试这样,在回调中使用this不会将原始元素定位为 jqXhr 对象,因此您可以将其缓存到变量中并使用它:

在 tha ajax 调用之前:

var flickrContainer = this; //this is already a jquery object here
$.getJSON(url, displayImages);
......

并在您的回调中将其用作:

  flickrContainer.append('<h2>'+photosetTitle+'</h2>');
  flickrContainer.append(theHtml);

演示

还有其他方法,例如使用 $.proxy function.bind 等将 ajax 回调的上下文绑定到元素的上下文。

 $.getJSON(url, displayImages.bind(this)); // or $.proxy(displayImages,this)

现在this函数内部表示 flickerContainer,所以你可以只做:

  this.append('<h2>'+photosetTitle+'</h2>');
  this.append(theHtml);

这是因为$(this)不是包含闪烁元素的jQuery对象,直到您return the object from the plugin

return this.each(function(){
    var $this = $(this);
    //now $this contains the jQuery object of the element/s bound to the plugin
});