jQuery insert div as certain index

后端 未结 9 688
眼角桃花
眼角桃花 2020-12-07 19:38

Say I have this:

1
2

bu

相关标签:
9条回答
  • 2020-12-07 20:36

    Use my simple plugin 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)
    
    0 讨论(0)
  • 2020-12-07 20:37

    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.

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

    0 讨论(0)
  • 2020-12-07 20:38

    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>");
    }
    

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

    0 讨论(0)
提交回复
热议问题