2012-12-20 78 views
0

我想將class .active添加到我的自定義引導分頁。如果nth-child(變量)有活躍的類,請將活動類添加到另一個元素的nth-child

目前,當我通過單擊分頁進行導航時,它工作良好,但是如果我使用箭頭,我的分頁中的下一個項目不會激活。

因此,基本上我想查看.carousel元素的哪個子元素處於活動狀態,並將活動類添加到我的分頁中的相同(例如第二個)子元素。

$('.sb-links a').click(function(q){ 
    q.preventDefault(); 
    targetSlide = $(this).attr('data-to')-1; 
    $('#myCarousel').carousel(targetSlide); 
    $('a').removeClass('active'); 
    $(this).addClass('active').siblings().removeClass('active'); 
}); 

該代碼看起來像這樣,但它甚至沒有工作,如果我手動鍵入子元素。

if ($('.carousel-inner div:nth-child(1)').hasClass('active')) { 
    $('.sb-links a:nth-child(1)').addClass('active'); 
}; 

在此先感謝您的幫助!

+3

也許[的jsfiddle(http://jsfiddle.net)將是有益的。 –

+0

一個fddle和/或一些標記。是的,那是票。 –

回答

1

嘗試:

// calculate the index you want 
var index = 1; 
// get the div at the calculated index 
var nthDiv = $('.carousel-inner div').eq(index); 

// check if div has class 
if (nthDiv.hasClass('active')) { 
    // add class to the hyperlink at the same index 
    $('.sb-links a').eq(index).addClass('active'); 
} 

下面是一個更完整的解決方案:

// attach an event which is triggered when transition is complete 
$('#myCarousel').on('slid', function (e) { 
    // get the index of the current frame 
    var index = $('.carousel-inner div').index('.active'); 
    // get all the slider buttons 
    var buttons = $('.sb-links a'); 
    // remove the 'active' class on all slider buttons 
    buttons.removeClass('active'); 
    // add the 'active' class on the button corresponding to the current frame 
    buttons.eq(index).addClass('active'); 
}) 
相關問題