gpt4 book ai didi

javascript - $(this) 不适用于 Flickr Gallery

转载 作者:行者123 更新时间:2023-11-30 05:42:24 25 4
gpt4 key购买 nike

请在此处查看此问题的代码笔: 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 对象,因此您可以将它缓存到一个变量中并使用它:

在 ajax 调用之前:

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

......

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

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

Demo

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

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

现在 this 在你的函数中代表了 flickerContainer 所以你可以这样做:

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

关于javascript - $(this) 不适用于 Flickr Gallery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20010811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com