jQuery 插入 div 作为某个索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3562493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:39:58  来源:igfitidea点击:

jQuery insert div as certain index

jquery

提问by DantheMan

Say I have this:

说我有这个:

<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.

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

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

假设我给插入的索引为 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.

如果我要插入 2 的索引,结果将是。

<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:

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

<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!

忘记最后一个例子的格式。在这个网站上复制和粘贴 HTML 代码的简单行为足以让我尖叫并拔出我的头发,我不想再花时间搞砸了!

回答by Andy Gaskell

As a function with a little better handling of 0:

作为对 0 处理更好的函数:

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


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

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

编辑:在第 n 个子选择器中添加括号以避免 NaN 错误。@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>

回答by Benjamin Gudehus

I had a similar problem. Unfortunately none of the solutions worked for me. So I coded it this way:

我有一个类似的问题。不幸的是,没有一个解决方案对我有用。所以我这样编码:

jQuery.fn.insertAt = function(index, element) {
  var lastIndex = this.children().size();
  if (index < 0) {
    index = Math.max(0, lastIndex + 1 + index);
  }
  this.append(element);
  if (index < lastIndex) {
    this.children().eq(index).before(this.children().last());
  }
  return this;
}

Examples for the problem:

问题示例:

$("#controller").insertAt(0, "<div>first insert</div>");
$("#controller").insertAt(-1, "<div>append</div>");
$("#controller").insertAt(1, "<div>insert at second position</div>");

Here are some examples taken from my unittests:

以下是我的单元测试中的一些示例:

$("<ul/>").insertAt(0, "<li>0</li>");
$("<ul/>").insertAt(0, "<li>0</li>").insertAt(1, "<li>1</li>");
$("<ul/>").insertAt(-1, "<li>-1</li>");
$("<ul/>").insertAt(-1, "<li>-1</li>").insertAt(0, "<li>0</li>");
$("<ul/>").insertAt(0, "<li>0</li>").insertAt(-1, "<li>-1</li>");
$("<ul/>").insertAt(-1, "<li>-1</li>").insertAt(1, "<li>1</li>");
$("<ul/>").insertAt(-1, "<li>-1</li>").insertAt(99, "<li>99</li>");
$("<ul/>").insertAt(0, "<li>0</li>").insertAt(2, "<li>2</li>").insertAt(1, "<li>1</li>");
$("<ul/>").insertAt(0, "<li>0</li>").insertAt(1, "<li>1</li>").insertAt(-1, "<li>-1</li>");
$("<ul/>").insertAt(0, "<li>0</li>").insertAt(1, "<li>1</li>").insertAt(-2, "<li>-2</li>");
$("<ul/>").insertAt(0, "<li>0</li>").insertAt(1, "<li>1</li>").insertAt(-3, "<li>-3</li>");
$("<ul/>").insertAt(0, "<li>0</li>").insertAt(1, "<li>1</li>").insertAt(-99, "<li>-99</li>");

Edit:It handles all negative indizes gracefully now.

编辑:它现在可以优雅地处理所有负面指标。

回答by Abdennour TOUMI

Use my simple plugin Append With Index:

使用我的简单插件Append With Index

$.fn.appendToWithIndex=function(to,index){
        if(! to instanceof jQuery){
            to=$(to);
        };
        if(index===0){
            $(this).prependTo(to)
        }else{
            $(this).insertAfter(to.children().eq(index-1));
        }
    };*

Now :

现在 :

$('<li>fgdf</li>').appendToWithIndex($('ul'),4)

Or :

或者 :

$('<li>fgdf</li>').appendToWithIndex('ul',0)

回答by Ash Blue

I found the listed solutions didn't work or were overly complicated. All you have to do is determine the direction you're appending from. Here is something simple written in an OOP manner for jQuery.

我发现列出的解决方案不起作用或过于复杂。您所要做的就是确定要附加的方向。下面是用 OOP 方式为 jQuery 编写的一些简单的东西。

$.fn.insertIndex = function (i) {
    // The element we want to swap with
    var $target = this.parent().children().eq(i);

    // Determine the direction of the appended index so we know what side to place it on
    if (this.index() > i) {
        $target.before(this);
    } else {
        $target.after(this);
    }

    return this;
};

You can simply use the above with some simple syntax.

您可以通过一些简单的语法简单地使用上面的内容。

$('#myListItem').insertIndex(2);

Currently using this on a visual editor project moving tons of data around via drag and drop. Everything is working great.

目前在一个可视化编辑器项目中使用它,通过拖放移动大量数据。一切都很好。



Edit: I've added a live interactive CodePen demo where you can play with the above solution http://codepen.io/ashblue/full/ktwbe

编辑:我添加了一个实时交互式 CodePen 演示,您可以在其中使用上述解决方案http://codepen.io/ashblue/full/ktwbe

回答by oLinkWebDevelopment

//jQuery plugin insertAtIndex included at bottom of post   

//usage:
$('#controller').insertAtIndex(index,'<div id="new">new</div>');

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

//example: use 0 or -int          
$('#controller').insertAtIndex(0,'<div id="new">new</div>');
  <div id="controller">
    <div id="new">new</div>
    <div id="first">1</div>
    <div id="second>2</div>
  </div>

//example: insert at any index     
$('#controller').insertAtIndex(1,'<div id="new">new</div>');
     <div id="controller">
        <div id="first">1</div>
        <div id="new">new</div>
        <div id="second>2</div>
     </div>

//example: handles out of range index by appending        
$('#controller').insertAtIndex(2,'<div id="new">new</div>');
      <div id="controller">
          <div id="first">1</div>
          <div id="second>2</div>
          <div id="new">new</div>
      </div>

/**!
 * jQuery insertAtIndex
 * project-site: https://github.com/oberlinkwebdev/jQuery.insertAtIndex
 * @author: Jesse Oberlin
 * @version 1.0
 * Copyright 2012, Jesse Oberlin
 * Dual licensed under the MIT or GPL Version 2 licenses.
*/

(function ($) { 
$.fn.insertAtIndex = function(index,selector){
    var opts = $.extend({
        index: 0,
        selector: '<div/>'
    }, {index: index, selector: selector});
    return this.each(function() {
        var p = $(this);  
        var i = ($.isNumeric(opts.index) ? parseInt(opts.index) : 0);
        if(i <= 0)
            p.prepend(opts.selector);
        else if( i > p.children().length-1 )
            p.append(opts.selector);
        else
            p.children().eq(i).before(opts.selector);       
    });
};  
})( jQuery );

回答by Phil Snook

This one works best for me,

这个最适合我

function SetElementIndex(element, index) {
            var Children = $(element).parent().children();
            var target = Children[index];

            if ($(element).index() > index) {
                if (target == null) {
                    target = Children[0];
                }
                if (target != element && target != null) {
                    $(target).before(element);
                }
            } else {
                if (target == null) {
                    target = Children[Children.length - 1];
                }
                if (target != element && target != null) {
                    $(target).after(element);
                }

            }
        };

回答by yPhil

Use .insertAfter():

使用.insertAfter()

$('<div class="new">').insertAfter($('div.first'));

回答by Ken Redler

If you need to do this a lot, you can wrap it in a little function:

如果你需要这样做很多,你可以把它包装在一个小函数中:

?var addit = function(n){
  $('#controller').append('<div id="temp">AAA</div>')
    .stop()
    .children('div:eq('+n+')')
    .before( $('#temp') );
} 

addit(2); // adds a new div at position 2 (zero-indexed)
addit(10); // new div always last if n greater than number of divs
addit(0); // new div is the only div if there are no child divs

If you're concerned about that temporary ID, you can add a final step to remove it.

如果您担心该临时 ID,您可以添加最后一步来删除它。

Edit:Updated to handle cases of zero children, and specified n> current number of divs.

编辑:更新以处理零子项的情况,并指定n> 当前 div 数。

回答by MoDFoX

You could always use prepend('#div');

你总是可以使用 prepend('#div');

ex.

前任。

$(document).ready(function(){

$('#first').prepend('<div id="new">New</div>');

});?

That would put "#new" before "#first" Not sure if that's what you want.

这会将“#new”放在“#first”之前。不确定这是否是您想要的。