跳转到特定项目时,更新当前的幻灯片数量 – Bootstrap 3 Carousel

当url匹配#时,我修改了标准的Boostrap 3 Carousel,以便能够跳转到特定的幻灯片。 它有效,但跳转到特定幻灯片时我的pager-text没有更新。 更新pager-textfunction仅在项目滑动后才起作用。 有人有解决方案吗?

我的HTML:

  
  • 1/{{ object.photo_set.count }}
  • 我的.js:

     $(document).ready(function() { //Initiate carousel $('.carousel').carousel({ interval: false }) $('.carousel').on('slid.bs.carousel', function () { var carouselData = $(this).data('bs.carousel'); var currentIndex = carouselData.getActiveIndex(); var total = carouselData.$items.length; // Display the current number of the slide var text = (currentIndex + 1) + "/" + total; $('.pager-text').text(text); // Update location based on slide (index is 0-based) window.location.hash = "#"+ parseInt($('.carousel .carousel-inner .item.active').index()+1); }); }); var url = document.location.toString(); if (url.match('#')) { // Clear active item $('.carousel .carousel-inner .item.active').removeClass('active'); // Activate item number #hash $('.carousel-inner div:nth-child(' + url.split('#')[1] + ')').addClass('active'); } 

    通过更新if (url.match('#')) { function中的寻呼机文本来修复它。 现在我可以输入www.mydomain.com/gallery-url/#4并将其发送到第四张图像,并且寻呼机文本显示为4/total

     $(document).ready(function() { var url = document.location.toString(); var totalItems = $('.item').length; //Initiate carousel $('.carousel').carousel({ interval: false }) $('.carousel').on('slid.bs.carousel', function () { var currentIndex = $('div.active').index() + 1; //Update pager-text $('.pager-text').text(''+currentIndex+'/'+totalItems+''); // Update location based on slide (index is 0-based) window.location.hash = "#"+ parseInt($('.carousel .carousel-inner .item.active').index()+1); }); if (url.match('#')) { // Clear active item $('.carousel .carousel-inner .item.active').removeClass('active'); // Activate item number #hash $('.carousel-inner div:nth-child(' + url.split('#')[1] + ')').addClass('active'); //Update pager-text $('.pager-text').text(''+url.split('#')[1]+'/'+totalItems+''); } }); 

    使用$('.carousel').carousel(number)跳转到特定幻灯片。

    来自bootstrap文档

    .carousel(数字)

    将轮播循环到特定帧(基于0,类似于数组)。

    有关使用哈希值跳转到特定幻灯片的更多信息,请参阅此问题 。

    此外,跳转到幻灯片的代码将在您的自定义代码更新pager-text之前执行,它也不会注册为“幻灯片”,因为您没有使用内置函数跳转到幻灯片。

    这样的东西可以给你你想要的结果。

     $(document).ready(function() { //Initiate carousel $('.carousel').carousel({ interval: false }) //Event: Update pager-text on slide $('.carousel').on('slid.bs.carousel', function () { ... }); //Jump to slide on page load $('.carousel').carousel(number); });