如何检查jQuery的FIND结果
这个问题在这里已经有了答案:
你非常接近!
只需检查selected.length
而不是selected
。
家长选择演示
$(document).ready(function() {
var parent = $(this).find(".parent");
if (parent) {
var selected = parent.find("div.selected");
if (selected.length) {
selected.css({
"color": "blue",
"border": "2px solid blue"
});
} else {
parent.css({
"color": "red",
"border": "2px solid red"
});
}
}
});
.ancestors * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
</script>
<div class="parent"> Parent Box
<div class="noselected"> Box A </div>
<div class="notselected"> Box B </div>
</div>
$(document).ready(function() {
var parent = $(this).find(".parent");
// check for the length property of the jquery object to get the number of elements matched
if (parent.length != 0) {
var selected = parent.find("div.selected");
// same goes here
if (selected.length != 0) {
selected.css({
"color": "blue",
"border": "2px solid blue"
});
} else {
parent.css({
"color": "red",
"border": "2px solid red"
});
}
}
});
.ancestors * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="ancestors">
<div class="parent"> Parent Box
<div class="notselected"> Box A </div>
<div class="notselected"> Box B </div>
</div>
</div>
链接地址: http://www.djcxy.com/p/83693.html