我遇到了相同类别的toggleClass函数问题
如何使其适用于相同的.toglebox和相同的.slider分隔..
提前感谢任何建议。
JS:
$('.togglebox').on('click', function() {
$('.slider').toggleClass('opened closed');
});
HTML看起来像这样:
<div class="containerslider">
<div class="slider opened">
<p>Lorep ipsum </p>
<p class="slider_wiecej">
<a href="/portfolio" target="_self" class="read_more_box_slider">more</a>
<a class="togglebox"></a>
</p>
</div>
</div>
<div class="containerslider">
<div class="slider opened">
<p>Lorep ipsum </p>
<p class="slider_wiecej">
<a href="/portfolio" target="_self" class="read_more_box_slider">more</a>
<a class="togglebox"></a>
</p>
</div>
</div>
答案 0 :(得分:1)
$('.togglebox').on('click', function() {
$(this) //refer to clicked element
.closest('.slider') //find nearest parent div with class 'slider'
.toggleClass('opened closed');//toggle the class
});
答案 1 :(得分:0)
在函数内使用this
对象是您所需要的。使用它来查找父.slider
$('.togglebox').on('click', function(e) {
e.preventDefault();
$(this).closest('div.slider').toggleClass('opened closed');
});
.opened{
border:1px solid red;
}
.closed{
border:1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="containerslider">
<div class="slider opened">
<p>Lorep ipsum </p>
<p class="slider_wiecej">
<a href="/portfolio" target="_self" class="read_more_box_slider">more</a>
<a class="togglebox">s</a>
</p>
</div>
</div>
<div class="containerslider">
<div class="slider opened">
<p>Lorep ipsum </p>
<p class="slider_wiecej">
<a href="/portfolio" target="_self" class="read_more_box_slider">more</a>
<a class="togglebox">s</a>
</p>
</div>
</div>