【问题标题】:Heading inside paragraph selector not working段落选择器内的标题不起作用
【发布时间】:2020-10-01 04:32:07
【问题描述】:
我想将<p> 标记的所有子项的背景颜色更改为绿色。但是我写的代码不起作用。但是,如果我将<p> 标签更改为<div>,它就可以工作了。但我需要它使用 jQuery 高级选择器处理 <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】:
h 不是p 的有效子代
Paragraph P
段落是块级元素,如果在关闭 </p> 标记之前解析另一个块级元素,则会自动关闭。
允许的内容:Phrasing content
渲染出来的 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");
$('<br />').insertBefore(this); // because of the inline-block
});
//Show only first 2 list item
$('ol li').hide().slice(0, 2).show();
})
.h6 {
display: inline-block;
font-size: .67em;
margin-top: 2.33em;
margin-bottom: 2.33em;
margin-left: 0;
margin-right: 0;
font-weight: bold;
}
<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="h6">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>