【问题标题】:jQuery append div to a specificjQuery 将 div 附加到特定的
【发布时间】:2011-02-16 02:45:49
【问题描述】:

如何使用 jQuery append 将元素附加到子元素的特定索引中,例如如果我有:

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

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

【问题讨论】:

  • 大概class=".container" 是错字吧?在类名中包含 . 是有效的,但不是您通常想要做的事情。

标签: javascript jquery append appendto


【解决方案1】:

有几个选项:

$("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'));

相同的选项,但使用“之前”插入到相同的位置:

$("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 选择器。但是,请注意:nth-child;与 eq() 和其他大部分内容不同,它的索引是从 1 开始的 (argh)。
  • 男人们,我总是忘记这一点。感谢您的提醒!
【解决方案2】:

("div.container div.item:eq(1)").after("&lt;element to insert&gt;")

【讨论】:

    【解决方案3】:
    $('.container').children()[1].append('whatever');
    

    【讨论】:

    • 这将不起作用,因为 [1] 返回不知道函数 'append()' 的本机 DOM 对象
    • 我应该避免 jQuery 问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2015-01-23
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 2010-11-11
    相关资源
    最近更新 更多