jQuery insert div as certain index

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

Say I have this:

1
2

bu

9条回答
  •  执笔经年
    2020-12-07 20:38

    As a function with a little better handling of 0:

    function insertAtIndex(i) {
        if(i === 0) {
         $("#controller").prepend("
    okay things
    "); return; } $("#controller > div:nth-child(" + (i) + ")").after("
    great things
    "); }

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

    function insertAtIndex(i) {
      if(i === 0) {
        $("#controller").prepend("
    okay things
    "); return; } $("#controller > div:nth-child(" + (i) + ")").after("
    great things
    "); } window.doInsert = function(){ insertAtIndex(2); }
    
    
    Item 1
    Item 2
    Item 4
    Item 5

提交回复
热议问题