我有问题检查如果hasClass,但我不明白为什么它不起作用。 我想,当另一个DIV中的第二个DIV有“在”中的“做某事”时。
的jQuery
if ( jQuery(".panel div:nth-child(2)").hasClass("in") ) {
jQuery(this).css("margin-top","200px");
console.log("has");
};
HTML
<div class="panel panel-default">
<div class="panel-heading"></div>
<div id="collapse1" class="accordion-body collapse in"></div>
</div>
编辑:对不起课程来了,当我打开手风琴时。
答案 0 :(得分:2)
如果条件只是块级语句,并且您不能使用$(this)
将if块称为范围。因此,您需要使用选择器本身,如:
if ( jQuery(".panel div:nth-child(2)").hasClass("in") ) {
jQuery(".panel div:nth-child(2)").css("margin-top","200px");
console.log("has");
};
简化版:
var selector = jQuery(".panel div:eq(1)");
if(selector.hasClass("in")){
selector.css("margin-top","200px");
}
我使用eq选择器,因为它是jQuery选择器而非nth-child。