我有一个jQuery语句,我想循环遍历所有div与类" test_section_holder"并将if / else语句应用于最近的" sub_ttl"格
这是我的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>
有什么想法吗?
答案 0 :(得分: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');
}