我只需要获取我在hasClass()
找到的类的父类,但它不起作用。
if ($('.test div').hasClass('has-error')) {
console.log($(this).parent().className)
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test'>
<div class='test2'>
<div class='has-error'></div>
</div>
</div>
&#13;
答案 0 :(得分:1)
您的代码存在的问题是this
将引用window
,因为您不在元素的范围内。
hasClass
在这里也有点多余,因为您可以直接选择具有给定类的元素,然后执行您的逻辑。
最后,请注意className
不是jQuery对象的有效属性。据推测attr('class')
就是你所需要的。试试这个:
var className = $('.test div.has-error').parent().attr('class');
console.log(className)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<div class="test2">
<div class="has-error"></div>
</div>
</div>
答案 1 :(得分:1)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test'>
<div class='test2'>
<div class='has-error'>
</div>
</div>
</div>
&#13;
public static String doLogin(String loginMail, String loginPassword) {
//Logging Retrofit
final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("###URLTOAPICALL###")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<JsonElement> call = service.doLogin(loginMail, loginPassword);
try {
Response response = call.execute();
if (response.isSuccessful()) {
// do your stuff and
return yourString;
}
}catch (IOException ex) {
ex.printStackTrace();
}
}
&#13;
像这样使用
答案 2 :(得分:1)
您可以使用filter
返回带有has-class
的元素,然后获取其父级的类。
var c = $('.test div').filter(function() {
return $(this).hasClass('has-error')
}).parent().attr('class')
console.log(c)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test'>
<div class='test2'>
<div class='has-error'>
</div>
</div>
</div>
&#13;