选择器>似乎没有在jquery中工作

时间:2015-01-15 03:46:19

标签: jquery jquery-plugins

我需要为所有直接孩子设置一个红色背景

  • #destinations 但我不想为
  • Paris
  • 设置背景,因为它不是#destinations的直接后代

    <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>
    

    2 个答案:

    答案 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