【问题标题】:How can I jQuery select a child div element?jQuery 如何选择子 div 元素?
【发布时间】:2014-09-02 16:05:22
【问题描述】:

我想根据父项的“id”以及其中一个子项的“类”来选择一个页面元素。这在子元素是 span 元素时有效,但在它是 div 时失败。

如何选择下面的特定 #testDiv .highlightme 项?

<script>  
        $(document).ready(function(){  
        $('#testSPAN .highlightme').css("background-color","yellow");  
        $('#testDIV  .highlightme').css("background-color","blue");  
    });  
</script>  



<p id="testSPAN">
    <span class="highlightme">
        This should highlight, and does. Good.
    </span>
</p>

<p id="testDIV">
    <div class="highlightme">
        This should highlight, but doesn't because it's in a div.
    </div>
</p>

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    p 标签只接受内联元素,而不接受其他块。 http://www.w3.org/TR/html401/struct/text.html#edef-P “P元素代表一个段落。它不能包含块级元素(包括P本身)。”

    这是你问题的核心,它是无效的 HTML。

    【解决方案2】:

    不管是 div 还是 span。您可以将类元素归因于任何标记。

    问题不是因为您的 jquery 代码,而是您将 div 元素包装在 p 中 在 html 中是不允许的! :)

    【讨论】:

      【解决方案3】:

      这里说的是真的,你不应该将块元素放在内联元素中,但是如果你不能修改 html 或者你不被允许,这里有一个对你有用的解决方法。 .

      $(document).ready(function(){
          $('[id*="test"]').each(function() {
              var bgcolor = "yellow";
              if ($(this).children('[class="highlightme"]')   ) {
                  $(this).children('[class="highlightme"]').css('background-color', bgcolor);
              }
              if ($(this).next().hasClass("highlightme") == true) {
                  $(this).next().attr('class', 'highlightme').css('background-color', bgcolor);
              }
          });
      });
      

      我希望这个小代码块可以帮助你,如果你还需要什么,请告诉我;)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        • 2012-05-20
        • 2021-10-03
        • 1970-01-01
        相关资源
        最近更新 更多