jQuery插入div作为特定索引 [英] jQuery insert div as certain index

查看:82
本文介绍了jQuery插入div作为特定索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个:

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

但是说我想根据我提供的索引任意插入一个新的div.

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

说我给插入的索引为0,结果应该是:

Say I gave the index to insert of 0, the result should be:

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

如果我要插入的索引为2,则结果为.

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>

如果我的索引为1,结果将是:

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>

只需忘记最后一个示例的格式即可.在此站点上复制和粘贴HTML代码的简单动作非常恐怖,足以让我大喊大叫并拔掉头发,我不想再花时间把它弄乱了!

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的函数:

As a function with a little better handling of 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个子选择器中添加了括号,以避免出现NaN错误. @hofnarwillie

Added parenthesis in the nth-child selector to avoid NaN errors. @hofnarwillie

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插入div作为特定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆