Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 如果hasClass不工作_Jquery - Fatal编程技术网

Jquery 如果hasClass不工作

Jquery 如果hasClass不工作,jquery,Jquery,我有一个问题要检查hasClass,但我不明白为什么它不能工作。 我想,当另一个DIV中的第二个DIV有类在做某事时 jQuery if ( jQuery(".panel div:nth-child(2)").hasClass("in") ) { jQuery(this).css("margin-top","200px"); console.log("has"); }; HTML 编辑:很抱歉,当我打开手风琴时,类来了。如果条件只是块级语句,您不能使用$this将If块作为作用

我有一个问题要检查hasClass,但我不明白为什么它不能工作。 我想,当另一个DIV中的第二个DIV有类在做某事时

jQuery

if ( jQuery(".panel div:nth-child(2)").hasClass("in") ) {
    jQuery(this).css("margin-top","200px");
    console.log("has");
};
HTML


编辑:很抱歉,当我打开手风琴时,类来了。

如果条件只是块级语句,您不能使用$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");
}

我使用了选择器,因为它是jQuery选择器,而不是第n个子项。

您正在检查一个不在HTML中的类。这是如何工作的?您是在寻找类。在中还是在寻找包含子字符串的类?我已经编辑了它。我在寻找这个类。在你的代码中,它可以根据你的要求很好地工作。它有作用它在控制台中写入元素,或者,更好的是,在if语句之前获取元素一次,并将其存储在var中,这样就不会对DOM进行两次查询。
var selector  = jQuery(".panel div:eq(1)");
if(selector.hasClass("in")){
  selector.css("margin-top","200px");
}