2015-08-25 43 views
0

我正在爲網站製作幻燈片。 圖像需要是背景圖像,我需要圖像標題作爲圖像頂部的報價。 問題是它顯示了所有圖像上第一個背景圖像的標題。不知怎的,我需要獲得單個圖像的標題。jQuery中每個圖像的標題

var $sliderImages = $('.slideshow .field-name-field-image-carousel img'); 
var $sliderImagesTitle = $sliderImages.attr('title'); 

    $sliderImages.each(function(i, elem) {       // create divs 
     var img = $(elem); 
     var div = $("<div class='sliderImage' />").css({ 
     background: "url(" + img.attr("src") + ") no-repeat", 
     }).append("<figcaption><span>" + $sliderImagesTitle + "</span></figcaption>"); 
     img.replaceWith(div);           // replace images with divs 
    }); 

    $('.sliderImage').wrap("<figure />");       // start by wrapping the rendered images 
    $('.slideshow figure:first-of-type').addClass('show');   // and choose which one to display first 

回答

0

當您在一組元素使用的.attr()吸氣版本,它會返回集合中的第一個元素的屬性值,而不是其他因素。

既然你是通過所有的圖像元素進行迭代,你可以用循環

var $sliderImages = $('.slideshow .field-name-field-image-carousel img'); 

$sliderImages.each(function (i, elem) { // create divs 
    var img = $(elem); 
    var div = $("<div class='sliderImage' />").css({ 
     background: "url(" + img.attr("src") + ") no-repeat", 
    }).append("<figcaption><span>" + img.attr('title') + "</span></figcaption>"); 
    img.replaceWith(div); // replace images with divs 
}); 

$('.sliderImage').wrap("<figure />"); // start by wrapping the rendered images 
$('.slideshow figure:first-of-type').addClass('show'); 
讀取值