我正在创建一个功能,可以自动将链接添加回Flickr发布到我博客上的图像,当只有一个图像时效果很好。一旦将更多图像添加到帖子中,我的功能就是将帖子中每张图片的标题添加到标题中,我似乎无法弄清楚为什么会发生这种情况。
的jQuery
$(".needs-credit").each(function() {
// Grab the image URL to put through the API call
var imgSrc = $(this).attr('src');
// If "flickr.com" is in the URL, run the function
if (!/flickr\.com$/i.test(imgSrc)) {
// Get the photo ID from the src
photoId = imgSrc.replace(/(.+\.[a-z]{2,4})\/(\d{3,5})\/(\d{7,15})(?:(?!ab).)*/ig, '$3');
//Call the Flicmr API to get the photo info as JSON
var apiUrl = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=c8c95356e465b8d7398ff2847152740e&photo_id=" + photoId + "&format=json&jsoncallback=?";
// Put a credit after the image using the JSON data
// NOTE that changing $('img') to $(this) breaks the script, I think because it's nested.
$.getJSON(apiUrl, function(data){
$('img').after('<a href="http://www.flickr.com/photos/'+data.photo.owner.nsid+'/'+data.photo.id+'/">'+data.photo.title._content+ ' by ' +data.photo.owner.username+'</a>');
})
}
})
我有一个丑陋的 CodePen Demo 显示问题。我唯一可以猜到的是,我在两处指定了这个类,但我似乎无法弄清楚在哪里。
答案 0 :(得分:0)
您需要指定要上传标题的图片。正如@dandavis所说,$("img")
将获得 ALL 图像,这就是为什么每张图片都会显示标题。
在.each
函数内,this
引用当前元素。但是,由于你在.getJson
的回调函数中,你需要以某种方式传递它:
//Option 1 - Using Closure
var $this = $(this);
$.getJSON(apiUrl, function(data){
$this.after('<a href="http://www.flickr.com/photos/'+data.photo.owner.nsid+'/'+data.photo.id+'/">'+data.photo.title._content+ ' by ' +data.photo.owner.username+'</a>');
})
//Option 2 - Explicitly binding this
$.getJSON(apiUrl, function(data){
$(this).after('<a href="http://www.flickr.com/photos/'+data.photo.owner.nsid+'/'+data.photo.id+'/">'+data.photo.title._content+ ' by ' +data.photo.owner.username+'</a>');
}.bind(this))
答案 1 :(得分:0)
尝试
$(this).after('<a href="http://www.flickr.com/photos/'+data.photo.owner.nsid+'/'+data.photo.id+'/">'+data.photo.title._content+ ' by ' +data.photo.owner.username+'</a>');
而不是
$('img').after('<a href="http://www.flickr.com/photos/'+data.photo.owner.nsid+'/'+data.photo.id+'/">'+data.photo.title._content+ ' by ' +data.photo.owner.username+'</a>');