开发者

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:

  1. .attr() can be used with a function as its second parameter. Normally it is used to set the attribute (this time alt) using the return value of the function. In this one, I don't return anything, just use it to loop through the alt attributes of the specified images.

  2. this here will refer to the img that is currently used

  3. .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>");
   }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜