[英]A condition to determine if the parent container child elements contains of specific class and do something
This is what I've tried so far. 到目前为止,这是我尝试过的。 But nothing of the three workaround works.
但是,这三种解决方法均无效。
I've tried using hasClass and find but no luck to make it work. 我试过使用hasClass并找到但没有运气使其工作。
HTML: HTML:
<div>Click me (I have a .cute class)
<p class="cute"></p>
</div>
<div>Click me (I don't a .cute class)
<p class="no-cute-class"></p>
</div>
jQuery: jQuery的:
$(document).ready(function(){
$("div").click(function(){
//Looking for siblings if has class of cute
if($(this).siblings().hasClass('cute')) {
alert("Found cute class");
} else {
alert("Didn't found cute class");
}
//jQuery hasClass
if($(this).hasClass('cute')) {
alert("Found cute class");
} else {
alert("Didn't found cute class");
}
//Using jQuery find
if($(this).find('.cute')) {
alert("Found cute class");
} else {
alert("Didn't found cute class");
}
});
});
I hope you want to search whether class called .cute
is inside your element. 我希望您想搜索名为
.cute
类是否在您的元素内。 But you can not traverse from p
to a div
. 但是您不能从
p
遍历到div
。 better change as below and try. 如下进行更好的更改,然后尝试。
You can use length
to find out any related class is there. 您可以使用
length
找出那里的任何相关类。
$("div").click(function(){ if($(this).find('.cute').length > 0){ alert('has class'); } else{ alert("no class"); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>Click me (I have a .cute class) <span class="cute"></span> </div> <div>Click me (I don't a .cute class) <span class="no-cute-class"></span> </div>
You can't wrap div
inside of p
tag. 您不能将
div
包装在p
标签内。
Because it renders in browser like below - 因为它在浏览器中呈现如下所示-
<p> <div> test </div> </p>
rendered in the DOM as: 在DOM中呈现为:
<p> </p> <div> test </div> <p> </p>
You can also use span
instead of div
like below or try JSFiddle 您还可以使用
span
,而不是div
像下面或尝试的jsfiddle
HTML Code- HTML代码
<div>
<p>Click me (I have a .cute class)
<span class="cute"></span>
</p>
<p>Click me (I don't a .cute class)
<span class="no-cute-class"></span>
</p>
</div>
JS Code- JS代码-
$("p").click(function() {
if ($(this).find('.cute').length) {
alert("Found Cute Class");
} else {
alert("Didn't found cute class");
}
});
If you want to use hasClass
try this: 如果要使用
hasClass
尝试以下操作:
$(document).ready(function(){ $("div").click(function(){ if($(this).find("p").hasClass("cute")){ alert("has cute"); } else{ alert("no class"); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div>Click me (I have a .cute class) <p class="cute"></p> </div> <div>Click me (I don't a .cute class) <p class="no-cute-class"></p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.