我需要为所有直接孩子设置一个红色背景
<html>
<head>
<title>Hijos Directos</title>
<script type="text/javascript" src="jquery-1.11.1.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#destinations > li").css("background-color","red");
});
</script>
</head>
<body>
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2>
<p>Plan your next adventure.</p>
<ul id="destinations">
<li>Rome</li>
<li>
<ul id="france">
<li>Paris</li>
</ul>
</li>
<li>Rio</li>
</ul>
</body>
答案 0 :(得分:2)
代码按预期工作。正在为法国的父li设置颜色,这导致整个li变为红色。子li从父li继承背景颜色。
检查任何Web浏览器检查器中的代码并查看此内容。
您可以尝试将其作为解决方案。 http://jsfiddle.net/uLfdnzc0/
$(document).ready(function(){
$("#destinations > li").css("background-color","red");
$("#destinations > li > ul").css("background-color","white");
});
答案 1 :(得分:1)
您可以使用:not
和:has
选择器来定位空的li元素:
$(document).ready(function(){
$("#destinations > li:not(:has(ul))").css("background-color","red");
});
<强> Working Demo 强>