简体   繁体   中英

How to set a background image from array of objects in Bootstrap carousel jQuery?

I have array of items, and every item(object) has property background where I store a url to image.This is my array 安慰

HTML:

<div id="myCarousel" class="carousel slide" data-ride="carousel">
        <!-- Indicators -->
        <ol class="carousel-indicators"></ol>
        <!-- Inner -->
        <div class="carousel-inner" role="listbox"></div>
        <!-- Controlls -->
        <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>
    </div>

and this is script from jQuery plugin:

$(items).each(function(index){
                $('.carousel-inner', self).append('<div class="item"><div class="container"><div class="carousel-caption">' + this.tournamentName + ' / ' + this.matchStatusName + '</div>');
                $('.carousel-inner div.item.active').css('background', 'url(' + this.background + ')');
                $('.carousel-indicators', self).append('<li data-target="#myCarousel" data-slide-to="'+index+'"></li>');
                $('.carousel-indicators li:first, .carousel-inner div.item:first', self).addClass('active');
                $(self).carousel();
            });

I tried to set background $('.carousel-inner .item.active').css('background', 'url(' + this.background + ')'); and also $('.carousel-inner div.item.active').css('background', 'url(' + this.background + ')'); but this won't work, it shows only first item with that image and stays that way until reach it to the end of slides.

Can someone help?

Your problem is with $('.carousel-inner div.item.active') , here you are trying to select the div with class active, But your div doesn't have active class yet.

Replace your this line of code

$('.carousel-inner div.item.active').css('background', 'url(' + this.background + ')');

With

$('.carousel-inner div.item:eq('+index+')').css('background', 'url(' + this.background + ')');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM