how to check for jQuery's FIND result
本问题已经有最佳答案,请猛点这里访问。
我一直在努力使用这个简单的脚本,并且在StackOverflow中找不到相关的问题。 这是我的问题。
我有两个盒子。 如果
如果未选中任何框,则应使用红色突出显示父框,如下所示:
这是一个片段:
1 2 3 4 5 6 7 8 9 10 11 12 | $(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"}); } } }); |
1 2 3 4 5 6 7 | .ancestors *:not(script) { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } |
1 2 3 4 5 6 7 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> <body class="ancestors"> Parent Box Box A Box B </body> |
请让我知道我错过了什么。 谢谢你的帮助!
你非常接近!
只需检查
父母选择的演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $(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" }); } } }); |
1 2 3 4 5 6 7 | .ancestors * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } |
1 2 3 4 5 6 7 8 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> Parent Box Box A Box B |
儿童选择演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $(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" }); } } }); |
1 2 3 4 5 6 7 | .ancestors * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } |
1 2 3 4 5 6 7 8 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> Parent Box Box A Box B |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $(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" }); } } }); |
1 2 3 4 5 6 7 | .ancestors * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } |
1 2 3 4 5 6 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> Parent Box Box A Box B |