How to append the proper attribute to a series of elements?
I have this bit of code:
if ($('.page-template-default .gallery img').attr('alt') !== undefined) {
$('.page-template-default .gallery li').append("<small>" + $('.page .gallery img').at开发者_JAVA技巧tr('alt') + "</small>");
}
Basically it appends the alt text of an image next to the image itself.
Problem is, I have a page with 10 images and the appended alt text is always the same, taken from the first image.
Is there way to return each alt text to the respective image?
Seems to be the easiest way:
$('.page-template-default .gallery img').attr('alt', function (i, alt) {
if (typeof alt != 'undefined' && alt!='') {
$(this).closest('li').append(alt);
}
});
jsFiddle Demo
For a little explanation:
.attr()
can be used with a function as its second parameter. Normally it is used to set the attribute (this timealt
) using the return value of the function. In this one, I don't return anything, just use it to loop through thealt
attributes of the specified images.this
here will refer to theimg
that is currently used.closest()
will return the closest parent of the image that matches the selector'li'
.
$('.page-template-default .gallery img').each(function(i,it) {
if ($(this).attr('alt') !== undefined) {
var li = $('.page-template-default .gallery li').get(i);
$( li ).append("<small>" + $(this).attr('alt') + "</small>");
}
});
You need to iterate through each img
if you want to use properties of each one like this.
var $imgs = $('.page-template-default .gallery li > a > img');
$imgs.each(function() {
var $img = $(this);
if ($img.attr('alt') !== undefined) {
var $li = $img.parent().parent();
$li.append("<small>" + $img.attr('alt') + "</small>");
}
});
var $imgs = $('.page-template-default .gallery img');
$imgs.each(function($img) {
if ($img.attr('alt') !== undefined) {
$img.after("<small>" + $img.attr('alt') + "</small>");
}
});
精彩评论