引导滑块冲突

时间:2018-02-22 21:34:41

标签: javascript jquery twitter-bootstrap

我的页面上有两个bootstrap轮播实例。我正在使用下面的代码随机化第一次轮播的页面刷新幻灯片。

//randomize the slider on page load 
var $item = $('.carousel .item');  
$item.eq(0).addClass('active'); 

var $numberofSlides = $('.item').length;
var $currentSlide = Math.floor((Math.random() * $numberofSlides));

$('.carousel-indicators li').each(function(){ 
  var $slideValue = $(this).attr('data-slide-to'); 
  if($currentSlide == $slideValue) {
    $(this).addClass('active');
    $item.eq($slideValue).addClass('active');
  } else {
    $(this).removeClass('active');
    $item.eq($slideValue).removeClass('active');
  }
}); 

但是,因为我在页面上有两个旋转木马。此代码导致其中一个在刷新页面时不总是加载。我怎样才能使用上面的代码定位一个轮播?我可以为其中一个添加ID并以某种方式合并吗?

1 个答案:

答案 0 :(得分:1)

您可以对脚本进行一些简单的更改,以便为每个轮播进行此操作:

//Do this for each .carousel
$(".carousel").each(function () { 
    //randomize the slider on page load
    //Find .item within the current .carousel
    var $item = $(this).find('.item');
    $item.eq(0).addClass('active'); 

    //Find .item within the current .carousel
    var $numberofSlides = $(this).find('.item').length;
    var $currentSlide = Math.floor((Math.random() * $numberofSlides));

    //Find .carousel-indicators li within the current .carousel
    $(this).find('.carousel-indicators li').each(function(){
        var $slideValue = $(this).attr('data-slide-to'); 
        if($currentSlide == $slideValue) {
            $(this).addClass('active');
            $item.eq($slideValue).addClass('active');
        } else {
            $(this).removeClass('active');
            $item.eq($slideValue).removeClass('active');
        }
    }); 
}); 

(我在添加和更改的行之前添加了一些注释)

如果您只想为一个轮播进行此操作,那么您应该给它一个ID,以便您可以定位它。

//randomize the slider on page load
var $item = $('#carouselid .item');
$item.eq(0).addClass('active'); 

var $numberofSlides = $('#carouselid .item').length;
var $currentSlide = Math.floor((Math.random() * $numberofSlides));

$('#carouselid .carousel-indicators li').each(function(){
    var $slideValue = $(this).attr('data-slide-to'); 
    if($currentSlide == $slideValue) {
        $(this).addClass('active');
        $item.eq($slideValue).addClass('active');
    } else {
        $(this).removeClass('active');
        $item.eq($slideValue).removeClass('active');
    }
}); 

在我输入carouselid的三个地方,您将使用您指定轮播的ID替换它。

相关问题