我一直在努力使用这个简单的脚本,但在StackOverflow中找不到相关的问题。这是我的问题。
我有两个盒子。如果<div class="notselected">
成为<div class="selected">
点击事件,则框会以蓝色突出显示。
如果未选择任何框,则应使用红色突出显示父框,如下所示:
这是一个片段:
$(document).ready(function(){
var parent = $(this).find(".parent");
if(parent) {
var selected = parent.find("div.selected");
if(selected) {
selected.css({"color": "blue", "border": "2px solid blue"});
}
else {
parent.css({"color": "red", "border": "2px solid red"});
}
}
});
&#13;
.ancestors *:not(script) {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="ancestors">
<div class="parent"> Parent Box
<div class="notselected"> Box A </div>
<div class="notselected"> Box B </div>
</div>
</body>
&#13;
请让我知道我错过了什么。谢谢你的帮助!
答案 0 :(得分:1)
你非常关闭!
只需检查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");
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="selected"> Box A </div>
<div class="notselected"> Box B </div>
</div>
答案 1 :(得分:0)
$(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"
});
}
}
});
&#13;
.ancestors * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
&#13;
<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>
&#13;