2013-11-15 43 views
2

請參閱我的codepen這裏這個問題: 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> 

回答

1

嘗試這種方式,使用this回調中不POSINT它是jqXhr對象的原始元素,所以不是你可以它來緩存一個變量,並使用它:

塔Ajax調用

前:

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

...... 

和insid Ë回調使用它作爲:

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

Demo

還有其他方面也一樣使用$.proxyfunction.bind等,以Ajax回調的背景下綁定到元素的上下文。

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

現在this自己的函數中表示flickerContainer,所以你可以這樣做:

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

完美的解釋和解決方案謝謝! –

+0

@DanielMurphy不客氣...... :) – PSL

0

這是因爲$(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 
});