简体   繁体   中英

jQuery toggleClass to parent class when child has a certain class

I'm using the Ratchet framework to prototype iPhone apps.

In Ratchet, they have toggles that uses the class toggle and onclick (or tap), it uses toggle and active .

Using jQuery, how can I toggle a class to the parent parent element, so when the toggle has the class active, it adds a class (say toggle-active ) to the parent parent element and when it doesn't have the class active, it removes have add that class. I've been looking at several different ways such as an if statement, onclick but I haven't found anything that works.

For example, this is what I tried:

jQuery

$(".toggle.active").click(function() {
    $(this).parent().parent().toggleClass("toggle-active");
});

Markup

<div class="toggle"><div class="toggle-handle"></div></div>

Is toggleClass the problem or is it the function?

on click.. check it has class active with hasClass if yes add required class to parent.parent.. if no remove it...

try this

 $(".toggle").click(function() {
   if($(this).hasClass('active'){
     $(this).parent().parent().addClass("toggle-active");
     //or $(this).parents().eq(2).addClass("toggle-active"); //for find() or closest()

   }else{
     $(this).parent().parent().removeClass("toggle-active");
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM