在另一个div上方添加一个div

6
<div>
  <div class="one">One</div>
  <div class="two">Two</div>
  <div class="three">Three</div>
  <div class="four">Four</div>
  <div class="five">Five</div>
</div>

我需要在三号和四号 div 之间添加一个 div,但是我不能在父 div 上使用任何定位方式(只能在其中的 div 上操作)。

jQuery('.four').parent().prepend('<div class="addme">Add Me!</div>');

可能你已经知道,使用".parent()"可以将内容添加到顶部,即在div One上方。如果不使用".parent()",则会在div Four内部添加该div,位于其内容之前。对于".append()"也是同样的道理。

有人有解决方案吗?

2个回答

18

您可以像这样使用.before().after()

jQuery('.four').before('<div class="addme">Add Me!</div>');
//or...
jQuery('.three').after('<div class="addme">Add Me!</div>');

相当确定我在谷歌上搜索了10分钟,但是没有找到.before或.after。我失败了。谢谢您,亲切的先生。 - wish_i_was_nerdy
2
@wish:不用谷歌!jQuery的API文档非常好;首先总是要检查那些。 - Matt Ball
<script type="text/javascript"> if (jQuery(window).width() > 770) { jQuery('#check-skiplinks').before('<div id="header-nav" class="skip-content"><?php echo $this->getChildHtml("topMenu") ?></div>'); } else if(jQuery(window).width()< 770) { jQuery('#check-skiplinks').after('<div id="header-nav" class="skip-content"><?php echo $this->getChildHtml("topMenu") ?></div>'); } </script> 你好,我需要执行这个操作,但它不起作用。请给我一些建议。 - Syed Ibrahim
我也谢谢你。 - vkelman

0
$('.three').after('<div class="addme">Add Me!</div>');

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