我有一个旋转着各种盒子的猫头鹰旋转木马。
当我单击框中的按钮时,我想将一个类切换到同一框中的div。
当我将其包裹在猫头鹰传送带中并进行初始化之前,它工作正常。之后,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可以很好地登录到控制台,但是该类不会添加到element中。完全没有错误。
答案 0 :(得分:2)
轮播中的每个元素都有相同的框列表,这意味着如果您有树箱,则轮播中的每个项目都包含#box-1
和#box-2
和#box-3
。因此,您需要获取最接近链接的框:
$(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>