使用jQuery在文本的第二段后追加HTML

使用jQuery在文本的第二段后追加HTML,jquery,Jquery,像这样使用HTML: <div class="content"> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> </div> 编辑: $('.content').each(function() { var $this = $(this); $this.append('<div i

像这样使用HTML:

<div class="content">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
</div> 
编辑:

 $('.content').each(function() {

    var $this = $(this);

    $this.append('<div id="link" class="link">Click Here</div>');

    $this.children('p:not(:first-child)').wrapAll('<div class="text" />');

} 
$('.content')。每个(函数(){
var$this=$(this);
$this.append('Click Here');
$this.children('p:not(:first children')).wrapAll('');
} 

并将文本div中的所有剩余段落(不包括前两段)

您的选择器不正确。您需要按如下方式使用:

$(函数(){
$('.content')。每个(函数(){
var$this=$(this);
$this.children('p:nth child(2)).append('Click Here');
$this.children('p:not(:first children')).wrapAll('');
});
});

第1款

第2款

第3款


我假设您正在遍历
.content
元素,因为它们有多个实例。这不是必需的,因为如果选择器包含元素集合,jQuery将自动为您执行此操作。然后您只需调用
append()
将内容添加到所需位置。请尝试以下操作:

$('.content p:nth child(2)')。追加('Click Here');

第1款

第2款

第3款

第1款

第2款

第3款


我编写了部分代码用于演示。请查看以下代码:

$.each($('.content p'), function (index, paragraph) {
    if (index == 1) { //second element
      $(paragraph).append('<div>some text</div>');
    }
});
$。每个($('.content p'),函数(索引,段落){
如果(索引==1){//第二个元素
$(段落).append('some text');
}
});

工作JSFIDLE:

这个
在代码中是对什么的引用?
$(这个)。查找('p:nth child(2)')。追加('Click Here'));
添加了完整的代码作为编辑。谢谢。我在下面为您添加了一个答案。我需要使用$this变量。请参见编辑。@Michelle请查看编辑。值得一提的是,使用原始答案比在每个
.content
元素上循环更有效。这会在第一段之后添加HTML链接,而不是第二段。@Michelle不,没有。请运行代码段。@Michelle,我已经更新了代码段以使用您的所有代码,您可以看到它按预期工作……谢谢,但我需要使用。append not.after。所以您希望
div
出现在
p
中吗?好的,为您的误解道歉。我已经为您更新了答案。这真的不是v一点也不难。为什么不利用Sizzle的力量呢?我只展示了解决OP问题的不同方法。
 $('.content').each(function() {

    var $this = $(this);

    $this.append('<div id="link" class="link">Click Here</div>');

    $this.children('p:not(:first-child)').wrapAll('<div class="text" />');

} 
$.each($('.content p'), function (index, paragraph) {
    if (index == 1) { //second element
      $(paragraph).append('<div>some text</div>');
    }
});