jQuery 方法在 Owl 轮播中不起作用

jQuery methods not working inside Owl Carousel

我有一个 owl 旋转木马,上面有各种盒子在旋转。

当我单击框内的按钮时,我想在同一框内将 class 切换为 div。

它工作正常,直到我将它包装在 owl 旋转木马中并对其进行初始化。在那之后,toggleClass 方法(和任何其他方法似乎)似乎停止工作。

$(document).ready(function() {

  $('.view-offer').click(function() {

    var linkID = $(this).data('id')
    var el = '#box-' + linkID
    $(el).toggleClass('test');

    console.log(el);

  });

  $(".offers-slider").owlCarousel({
    nav: false,
    autoPlay: false,
    navText: [
      "<i class='fa fa-angle-left'></i>",
      "<i class='fa fa-angle-right'></i>"
    ],
    loop: true,
    dots: false,
    items: 3
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" rel="stylesheet" />
<div class="owl-carousel owl-theme offers-slider">

  <div class="item">
    <a href="#!" class="view-offer" data-id="1">View</a>
    <div id="box-1">
      Box 1
    </div>
  </div>

  <div class="item">
    <a href="#!" class="view-offer" data-id="2">View</a>
    <div id="box-2">
      Box 2
    </div>
  </div>

  <div class="item">
    <a href="#!" class="view-offer" data-id="3">View</a>
    <div id="box-3">
      Box 3
    </div>
  </div>

</div>

linkID 将正常登录到控制台,但 class 不会添加到元素。完全没有错误。

轮播中的每个元素都有相同的框列表,这意味着如果轮播中的每个项目都有树框,同时包含 #box-1#box-2#box-3。所以你需要找到离你最近的盒子 link:

$(document).ready(function() {

  $('.view-offer').click(function() {

    var linkID = $(this).data('id')
    var el = '#box-' + linkID
    $(this).siblings(el).toggleClass('test');

    console.log(el);

  });

  $(".offers-slider").owlCarousel({
    nav: false,
    autoPlay: false,
    navText: [
      "<i class='fa fa-angle-left'></i>",
      "<i class='fa fa-angle-right'></i>"
    ],
    loop: true,
    dots: false,
    items: 3
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" rel="stylesheet" />
<div class="owl-carousel owl-theme offers-slider">

  <div class="item">
    <a href="#!" class="view-offer" data-id="1">View</a>
    <div id="box-1">
      Box 1
    </div>
  </div>

  <div class="item">
    <a href="#!" class="view-offer" data-id="2">View</a>
    <div id="box-2">
      Box 2
    </div>
  </div>

  <div class="item">
    <a href="#!" class="view-offer" data-id="3">View</a>
    <div id="box-3">
      Box 3
    </div>
  </div>

</div>