假设我有这个:

<div id="controller">
 <div id="first">1</div>
 <div id="second>2</div>
</div>

but say I wanted to insert a new div arbitrarily based on an index I supply.

假设我给出了插入0的索引,结果应该是:

<div id="controller">
  <div id="new">new</div>
  <div id="first">1</div>
  <div id="second">2</div>
</div>

and if I have an index to insert of 2 the result would be.

<div id="controller">
  <div id="first">1</div>
  <div id="second">2</div>
  <div id="new">new</div>
</div>

and if I give an index of 1 the result would be:

<div id="controller">
  <div id="first">1</div>
  <div id="new">new</div>
  <div id="second">2</div>
</div>

just forget that last example's format. The simple act of copying and pasting HTML code on this site is horrific enough to make me about scream and pull my hair out and I dont want to spend anymore time messing with it!

推荐答案

作为一个更好地处理0的函数:

function insertAtIndex(i) {
    if(i === 0) {
     $("#controller").prepend("<div>okay things</div>");        
     return;
    }


    $("#controller > div:nth-child(" + (i) + ")").after("<div>great things</div>");
}

编辑:在第n个子 Select 器中添加括号,以避免出现NaN错误@霍夫纳威利

function insertAtIndex(i) {
  if(i === 0) {
    $("#controller").prepend("<div>okay things</div>");        
    return;
  }


  $("#controller > div:nth-child(" + (i) + ")").after("<div>great things</div>");
}

window.doInsert = function(){
  insertAtIndex(2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="controller">
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 4</div>
  <div>Item 5</div>
</div>
<button onclick="doInsert()">Insert "great things" at index 2.</button>

Jquery相关问答推荐

如何使用 JQuery 将详细信息中的项目包装在容器中?

如何限制select2中的字符?

$(document).ready(function() VS $(function(){

模糊事件阻止点击事件工作?

window.onbeforeunload 和 window.onunload 在 Firefox、Safari、Opera 中不起作用?

验证外部脚本是否已加载

Javascript中的选定文本事件触发器

datatable jquery - 表头宽度与正文宽度不对齐

jQuery - 多个 :not Select 器

在 jQuery UI 自动完成上没有检测到结果

如何使用 Twitter Bootstrap 自动关闭alert

.apply jQuery 函数是什么?

Jquery:如何判断元素是否具有某些 css 类/样式

bootstrap 模式:关闭当前,打开新

如何重新加载/刷新 jQuery 数据表?

如何使用 javascript 展开和折叠

为什么要定义一个匿名函数并将 jQuery 作为参数传递给它?

如何判断值是否为 JSON 对象?

使用 jQuery 检测元素内容的变化

jQuery 将换行符转换为 br (nl2br 等效)