jQuery将div添加到特定位置

11

如何使用jQuery append在子元素的特定索引处添加一个元素,例如,如果我有:

<div class=".container">
   <div class="item"><div>
   <div class="item"><div>
   <div class="item"><div>
   <div class="item"><div>
</div>

我想在第二个和第三个项目之间添加另一个项目?


6
大概 class=".container" 是笔误了吧?在类名中使用 . 是合法的,但通常不建议这样做。 - bobince
3个回答

21

有几个选择:

$("div.container div.item").eq(2).after($('your html'));

$("div.container div.item:nth-child(3)").after($('your html'));

$($("div.container div.item")[2]).after($('your html'));

相同的选项,但是使用 "before" 在相同的位置进行插入:

$("div.container div.item").eq(3).before($('your html'));

$("div.container div.item:nth-child(4)").before($('your html'));

$($("div.container div.item")[3]).before($('your html'));

1
使用 eq() 方法而不是非 CSS 标准(因此效率较低)的 :eq 选择器可以获得 +1 的性能提升。但是,要小心 :nth-child;与 eq() 和大多数其他内容不同,它的索引是基于 1 的(呃)。 - bobince
兄弟,我总是忘记这个。谢谢你提醒我! - user875139

4

("div.container div.item:eq(1)").after("<element to insert>")

的意思是在 div.container 中第二个 div.item 后面插入一个元素。

-1
$('.container').children()[1].append('whatever');

1
这将不起作用,因为[1]返回本地DOM对象,它不知道函数'append()'的存在。 - jAndy
2
我应该避免jQuery相关的问题。 - Fletcher Moore

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接