获取图像的alt属性,将其添加到新div中

时间:2016-08-17 11:38:06

标签: jquery html arrays image attr

我有一个滑块,我尝试在滑块中的每个图像上创建一个新的div,它应该显示每个图像的alt属性。 我只设法得到第一张图片的替代文字,而不是出现在每张图片上,但每张图片都有自己的替代文字。所以这不是我需要的解决方案..我试图找到正确的解决方案,但却被困在这一点..

jQuery(function($){
    $("<div class='image_title'></div>").insertAfter(".et_pb_gallery_image .et_overlay");
    var title = $(".et_pb_gallery_image img").attr("alt");
    $(".image_title").text(title);
});

我也试过这个:

jQuery(function($){
    $("<div class='image_title'></div>").insertAfter(".et_pb_gallery_image .et_overlay");
    $(".image_title").each(function(){    
        var levelArray = $(".et_pb_gallery_image img").map(function() {
        return $(this).attr("alt");
    }).get();
    $( ".image_title" ).html(title);
    });
});

但这会显示每张图片上的每个替代文字......

我使用带有内置内容图像滑块的主题的wordpress&gt;但是内置滑块仅在灯箱显示/弹出时才显示titel和alt属性。我希望alt图像在图像上可见,这就是我想要做的。

滑块在html页面中的显示方式的HTML片段:

&#13;
&#13;
<div class="slider">
  <div class="post_gallery">
      <div class="gallery_item">
          <div class="et_pb_gallery_image">
              <a href="#" title="image title 01">
                 <img src="image.jpg" alt="Pic 01">
                 <span class="et_overlay"></span>
                 <!-- this is created with the code I used -->
                 <div class="image_title">Pic 01</div>
              </a>
          </div>
      </div>
  </div>
  
  <div class="post_gallery">
      <div class="gallery_item">
          <div class="et_pb_gallery_image">
              <a href="#" title="image title 02">
                 <img src="image.jpg" alt="Pic 02">
                 <!-- but the second image also has "Pic 01" instead of "Pic 02" -->
                 <div class="image_title">Pic 01</div>
              </a>
          </div>
      </div>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

试试这个:

$(".et_pb_gallery_image .et_overlay").each(function(){
  $("<div class='image_title'></div>").insertAfter(this);
  var thisImage = $(this).parents('.et_pb_gallery_image').find('img');
  var title = thisImage.attr('alt');
  $(this).siblings('.image_title').html(title);
});
相关问题