Jquery for 标签在高级选择器中不起作用

问题描述 投票:0回答:1

我想将<p>标签的所有子项的背景颜色更改为绿色。但是我编写的代码不起作用。但是,如果我将<p>标签更改为<div>,则可以正常工作。但是我需要它使用jQuery Advanced Selectors在<p>标签上工作

代码:

$(document).ready(() => {
  //Change background color of children to green
  //Below code is not working
  $("#intro").children().each(function() {
    $(this).css("background-color", "green");
  });
  //Show only first 2 list item
  $('ol li').hide().slice(0, 2).show();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<p id="intro">jQuery is a lightweight, "write less, do more" JavaScript library.
  <h6>The purpose of jQuery is to make it much easier to use JavaScript on your website</h6>
</p>
<ol>
  <li>HTML/DOM manipulation</li>
  <li>CSS manipulation</li>
  <li>Effects and animations</li>
  <li>AJAX</li>
</ol>
javascript html jquery css jquery-selectors
1个回答
0
投票

[h不是p的有效子代

渲染的HTML变为

<p id="intro">jQuery is a lightweight, "write less, do more" JavaScript library.
</p><!-- inserted by browser -->
<h6>The purpose of jQuery is to make it much easier to use JavaScript on your website</h6>
<p><!-- inserted by browser -->
</p>

您可以这样做:

$(document).ready(() => {
  //Change background color of children to green
  //Below code is now working
  $("#intro").children().each(function() {
    $(this).css("background-color", "green");
  });
  //Show only first 2 list item
  $('ol li').hide().slice(0, 2).show();
})
.header {
  display: inline-block;
  font-size: smaller
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<p id="intro">jQuery is a lightweight, "write less, do more" JavaScript library.
  <span class="header">The purpose of jQuery is to make it much easier to use JavaScript on your website</span>
</p>
<ol>
  <li>HTML/DOM manipulation</li>
  <li>CSS manipulation</li>
  <li>Effects and animations</li>
  <li>AJAX</li>
</ol>
© www.soinside.com 2019 - 2024. All rights reserved.