使用jQuery插入HTML时,最好使用.append还是.after?
根据用于jQuery API的描述,它们几乎相同,但是对于学习jQuery的人来说,很难知道在这个例子中哪个更好。
.after 说明:在匹配元素集合中的每个元素之后插入由参数指定的内容。
.append 说明:将参数指定的内容插入匹配元素集中每个元素的末尾。
基于以下示例,我认为.after应该用于添加读取更多的切换链接而不是.append,因为它添加了所有其他HTML元素。
$('.content').each(function() {
var $this = $(this);
if ($this.children('p').length >= 2) {
$this.append('<div id="toggle">Read More</div>');
}
});
$('.content p:last-child').each(function() {
var $this = $(this);
if ($this.children('p').length >= 2) {
$this.after('<div id="toggle-2" class="btn">2nd Read More</div>');
}
});
&#13;
.content {
margin-bottom:10px;
}
.content p {
margin: 0;
}
.content #toggle {
margin-top: 5px;
color: red;
}
.content #toggle-2 {
margin-top: 15px;
color: blue;
}
&#13;
<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>
&#13;