2015-06-19 2 views
0

У меня есть заявление JQuery, что я хочу, чтобы перебрать все дивы с классом «test_section_holder» и применить, если/другое заявление ближайшего «sub_ttl» ДИВJQuery .each если/другое заявление

Вот мой JQuery - где бы я помещаю .each

$(function() { 
    // This will fire when document is ready: 
    $('.sub_ttl').click(function() { 
     // This will fire each time the window is resized: 
     if($(window).width() >= 980) { 
      // if larger or equal 
      if($('#test').hasClass('desktop_refine') && $(".test_section_holder").is(":visible")) 
       { 
        $(".test_section_holder").closest(".test_section").find(".sub_ttl").toggleClass("mobileopen").removeClass("on"); 
       } 
      } else { 
       // if smaller 
       $('#test').addClass('mobile_refine').removeClass('desktop_refine'); 
     } 
    }).resize(); 
}); 

А вот мой HTML

<div id="test"> 
    <div class="test_section"> 
     <span class="sub_ttl">Sub title 1</span> 
     <div class="test_section_holder"> 
      Section 1 
     </div> 
    </div> 
    <div class="test_section"> 
     <span class="sub_ttl">Sub title 2</span> 
     <div class="test_section_holder"> 
      Section 2 
     </div> 
    </div> 
</div> 

И CSS

<style> 
#test {height:auto; width:100%; overflow:hidden; font-family:arial; text-indent:15px;} 
#test .test_section {height:auto; width:100%; overflow:hidden;} 
#test .test_section .sub_ttl {height:auto; width:100%; background:#000000; color:#ffffff; display:block; padding:15px 0;} 
#test .test_section .test_section_holder {display:none; margin-bottom:20px; margin-top:10px;} 
#test .test_section .sub_ttl.on {background:yellow; color:#000000;} 

#test .test_section .sub_ttl.mobileopen {background:red;} 
#test .test_section .sub_ttl.mobileclosed {background:green;} 
#test .test_section .sub_ttl.desktopopen {background:blue;} 
#test .test_section .sub_ttl.desktopclosed {background:pink;} 

@media only screen and (min-width:980px){ 
#test {width:300px;}  
#test .test_section .test_section_holder {display:block;} 
} 
</style> 

Любые идеи?

+2

В чем проблема? Что происходит в сравнении с тем, что вы желаете? –

+0

Я хочу добавить класс в sub_ttl div на основе условия инструкции if/else - если нужно будет применять к каждому sub_ttl div индивидуально на основе соответствующего test_section_holder div –

+0

Итак, вы хотите заменить метод click на цикл или цикл внутри клика? –

ответ

0

Я думаю, что это то, что вы после:

if ($('#test').hasClass('desktop_refine') { 
    $(".test_section_holder").is(":visible").each(function() { 
     $(this).closest(".test_section").find(".sub_ttl") 
      .toggleClass("mobileopen") 
      .removeClass("on"); 
    }); 
} else { 
    // if smaller 
    $('#test').addClass('mobile_refine').removeClass('desktop_refine'); 
} 
+0

'.is()' возвращает 'true' или' false', а не коллекцию. Используйте '.filter()' вместо '.is()' или измените селектор на '.test_section_holder: visible' – Barmar