javascript - Run script for each image in the same class -
javascript - Run script for each image in the same class -
i'm creating function automatically adds link image posted blog flickr , works when there's 1 image. more images added post, function adding title every image in post caption , can't seem figure out why that's happening.
jquery
$(".needs-credit").each(function() { // grab image url set through api phone call var imgsrc = $(this).attr('src'); // if "flickr.com" in url, run function if (!/flickr\.com$/i.test(imgsrc)) { // photo id src photoid = imgsrc.replace(/(.+\.[a-z]{2,4})\/(\d{3,5})\/(\d{7,15})(?:(?!ab).)*/ig, '$3'); //call flicmr api photo info json var apiurl = "https://api.flickr.com/services/rest/?method=flickr.photos.getinfo&api_key=c8c95356e465b8d7398ff2847152740e&photo_id=" + photoid + "&format=json&jsoncallback=?"; // set credit after image using json info // note changing $('img') $(this) breaks script, 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+ ' ' +data.photo.owner.username+'</a>'); }) } })
i've got ugly codepen demo showing problem. thing can guess i'm specifying class somewhere twice, can't seem figure out where.
you need specify image you're uploading caption for. @dandavis said, $("img")
all images, why every image getting caption.
inside .each
function, this
refers current element. however, since you're within callback function of .getjson
, need pass in way:
//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+ ' ' +data.photo.owner.username+'</a>'); }) //option 2 - explicitly binding $.getjson(apiurl, function(data){ $(this).after('<a href="http://www.flickr.com/photos/'+data.photo.owner.nsid+'/'+data.photo.id+'/">'+data.photo.title._content+ ' ' +data.photo.owner.username+'</a>'); }.bind(this))
javascript jquery
Comments
Post a Comment