【问题标题】:Using jQuery/js counter with Owl Carousel to display two digits in navigation使用带有 Owl Carousel 的 jQuery/js 计数器在导航中显示两位数
【发布时间】:2026-01-06 06:55:01
【问题描述】:

我正在使用 Owl Carousel 2 并创建当前格式为 的自定义导航。我想实现两位数编号,所以对于小于 10 的数字,我需要在前面添加一个 0。理想情况下,格式应如下所示:。我尝试了一个 if/then 但无法让它与这里的计数器的编写方式一起工作。有没有办法修改这段代码来实现这种格式?

JS/jQuery

<script>
$(function(){
var owl = $('.owl-carousel');
owl.owlCarousel({
  items:1,
  loop: false,
  onInitialized  : counter, //When the plugin has initialized.
  onTranslated : counter //When the translation of the stage has finished.
});

$(".next").click(function() {
    owl.trigger('next.owl.carousel');
});
$(".prev").click(function() {
    owl.trigger('prev.owl.carousel');
});

function counter(event) {
   var element   = event.target;
    var items     = event.item.count;     // Number of items
    var item      = event.item.index + 1;     // Position of the current item

  $('.counter').html(item+" / "+items)
}
});
</script>

HTML

<div class="gfoot">
    <div><h5><a class="prev">&lt; </a>
        <span class="counter"></span>
    <a class="next"> &gt;</a></h5></div>
</div>

【问题讨论】:

    标签: javascript jquery owl-carousel-2


    【解决方案1】:

    尝试替换这一行:

    $('.counter').html(item+" / "+items)
    

    用这一行:

    $('.counter').html((item < 10 ? '0' : '') + item + " / " + items)
    

    【讨论】:

    • 这很完美!我也将它添加到第二部分:$('.counter').html((item &lt; 10 ? '0' : '') + item + "/" + (items &lt; 10 ? '0' : '') + items)