简体   繁体   English

如何从Bootstrap轮播jQuery中的对象数组设置背景图像?

[英]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 我有一组项目,每个项目(对象)都有属性背景,我在其中存储图像的URL。这是我的数组 安慰

HTML: 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: 这是jQuery插件的脚本:

$(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 + ')'); 我试图设置背景$('.carousel-inner .item.active').css('background', 'url(' + this.background + ')'); and also $('.carousel-inner div.item.active').css('background', 'url(' + this.background + ')'); 以及$('.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. 您的问题在于$('.carousel-inner div.item.active') ,在这里您试图选择具有活动类的div,但是您的div还没有活动的类。

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 + ')');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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