如何使用jQuery append在子元素的特定索引处添加一个元素,例如,如果我有:
<div class=".container">
<div class="item"><div>
<div class="item"><div>
<div class="item"><div>
<div class="item"><div>
</div>
我想在第二个和第三个项目之间添加另一个项目?
如何使用jQuery append在子元素的特定索引处添加一个元素,例如,如果我有:
<div class=".container">
<div class="item"><div>
<div class="item"><div>
<div class="item"><div>
<div class="item"><div>
</div>
我想在第二个和第三个项目之间添加另一个项目?
有几个选择:
$("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'));
eq()
方法而不是非 CSS 标准(因此效率较低)的 :eq
选择器可以获得 +1 的性能提升。但是,要小心 :nth-child
;与 eq()
和大多数其他内容不同,它的索引是基于 1 的(呃)。 - bobince("div.container div.item:eq(1)").after("<element to insert>")
div.container
中第二个 div.item
后面插入一个元素。$('.container').children()[1].append('whatever');
class=".container"
是笔误了吧?在类名中使用.
是合法的,但通常不建议这样做。 - bobince