我一直在尝试检查一个类是否存在于div中.但是总是导致长度为0.这是我的代码:
<div id="accordion2" class="accordion" > <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapSEOne"> <div class="align-nav arrow-active">OSTOMY PRODUCTS</div></a> </div> <div id="collapSEOne" class="accordion-body in collapse"> <div class="accordion-inner"> <ul> <li><a href="#">Professional Resources</a></li> <li><a href="#">One-piece Pouching</a></li> </ul> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo"> <div class="align-nav arrow-inactive">LEARNING CENTER</div> </a> </div> <div id="collapseTwo" class="accordion-body collapse"> <div class="accordion-inner"> <ul> <li><a href="#">Videos</a></li> <li><a href="#">Before Your Surgery</a></li> </ul> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseThree"> <div class="align-nav">PROFESSIONAL RESOURCES </div> </a> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseThree"> <div class="align-nav">PROFESSIONAL RESOURCES </div> </a> </div> </div> </div>
对于前两个div $(this).find(‘accordion-body’),长度应为1.但仍然显示为0.我的Jquery CODE如下:
$('.accordion-heading').click(function() { if($(this).find('accordion-body').exist()) { alert('hi'); if($(this).find('.collapsed').length > 0) { alert('hi'); //$(this).find('.accordion-toggle .align-nav').removeClass('arrow-active').addClass('arrow-inactive'); } else { alert('hi'); //$(this).find('.accordion-toggle .align-nav').removeClass('arrow-inactive').addClass('arrow-active'); } } });
解决方法
你应该在查找中选择一个类选择器,因为你正在搜索类..而且手风琴是父母下属使用parent()
尝试这个
$(this).parent().find('.accordion-body').length == 1;
或者你可以使用hasClass()