Jquery toggleclass为相同的类分隔

时间:2016-02-10 11:48:50

标签: jquery toggleclass

我遇到了相同类别的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>

2 个答案:

答案 0 :(得分:1)

使用closestparents

$('.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>