gpt4 book ai didi

javascript - 当超过 1 段时,为每篇文章的第 1 段后附加 div

转载 作者:行者123 更新时间:2023-11-30 15:01:18 24 4
gpt4 key购买 nike

只有当每篇文章至少有 2 个段落时,是否可以在每篇文章的第一段文本后附加(而不是使用 .after())HTML div,否则不要添加 div?

 $('.content').each(function() {
var $this = $(this);
if ($this.children('p').length >= 2) {
$this.append('<div id="toggle">Read More</div>');
$('p').not('p:first-child').wrap('<div class="text" />');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="content">
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
</div>

<div class="content">
<p>This is an example of a paragraph</p>
</div>

<div class="content">
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
</div>

这就是我需要实现的目标。只有当每个内容 div 的文本超过 1 段时,才会添加 div。

<div class="content">
<p>This is an example of a paragraph</p>
<div class="text" />
<p>This is an example of a paragraph</p>
<div id="toggle">Read More</div>
</div>

<div class="content">
<p>This is an example of a paragraph</p>
</div>

<div class="content">
<p>This is an example of a paragraph</p>
<div class="text" />
<p>This is an example of a paragraph</p>
<div id="toggle">Read More</div>
</div>

最佳答案

你离得太近了!

$('.content').each(function() {
var $this = $(this);
if ($this.children('p').length >= 2) {
$this.append('<div id="toggle">Read More</div>');
}
});
.content {
border:1px solid red;
margin-bottom:10px;
}

.content p {
margin:0;
}

.content #toggle {
margin-top:5px;
color:cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="content">
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
</div>

<div class="content">
<p>This is an example of a paragraph</p>
</div>

<div class="content">
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
</div>


<div class="content">
<p>This is an example of a paragraph</p>
</div>


<div class="content">
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
</div>

关于javascript - 当超过 1 段时,为每篇文章的第 1 段后附加 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com