点击计数器 Bootstrap 轮播按钮

Click counter Bootstrap carousel button

不幸的是,这是一个非常愚蠢的问题。但是,我无法弄清楚如何为 Bootstrap 轮播按钮制作一个有效的点击计数器。问题是上一个和下一个图标的跨度元素。

按钮计数器不计算相应跨度元素上的点击次数。

$('button').click(function(btn) {
  btn.target.dataset.click_counter_hidden = (+btn.target.dataset.click_counter_hidden || 0) + 1;
  $('#click_search_left').val($('button[data-id="slider_left"]').attr("data-click_counter_hidden") || 0);
  $('#click_search_right').val($('button[data-id="slider_right"]').attr("data-click_counter_hidden") || 0);
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>


<div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel" data-bs-interval="false">

  <div class=class="carousel-item active">
    <div class="carousel-item" id="example1">
      <img id="example_1" src="https://picsum.photos/200/300" class="d-block w-100" alt="example_1">
    </div>
    <div class="carousel-item" id="example2">
      <img id="example_2" src="https://picsum.photos/200/300" class="d-block w-100" alt="example_2">
    </div>
    <div class="carousel-item" id="example3">
      <img id="example_3" src="https://picsum.photos/200/300" class="d-block w-100" alt="example_1">
    </div>
  </div>

  <button type="button" id='slider_left' data-id="slider_left" class="carousel-control-prev tracked_element" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
    <span class="carousel-control-prev-icon" id="prev_icon" aria-hidden="true"></span>
    <span class="visually-hidden">Previous</span>
  </button>
  
  <button type="button" id='slider_right' data-id="slider_right" class="carousel-control-next tracked_element" data-bs-target="#carouselExampleControls" data-bs-slide="next">
    <span class="carousel-control-next-icon" id="next_icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
  </button>
  
</div>

<input type="hidden" name="click_search_left" id="click_search_left" value="0" />
<input type="hidden" name="click_search_right" id="click_search_right" value="0" />

将您的计数器数据属性添加到两个按钮(这只是为了帮助初始化)。

<button data-click_counter_hidden="0">

检查按钮上是否有点击事件。如果不是,它一定是子 span 元素,所以获取父元素(按钮)。

$('button').on('click', function(e){
  
  $t = $(e.target);
  if (!$t.is('button')){
    $t = $t.parent();
  }
  
  clicks = parseInt($t.data('click_counter_hidden')) + 1;
  $t.data('click_counter_hidden', clicks);
  // display counter value elsewhere if needed

});