developer tip

jQuery는 div를 특정 인덱스로 삽입

optionbox 2020. 11. 1. 17:39
반응형

jQuery는 div를 특정 인덱스로 삽입


내가 이것을 가지고 있다고 말하십시오.

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

그러나 내가 제공하는 인덱스를 기반으로 임의로 새 div를 삽입하고 싶다고 말합니다.

0을 삽입하기 위해 색인을 부여했다고 가정하면 결과는 다음과 같습니다.

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

2를 삽입 할 인덱스가 있으면 결과가됩니다.

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

인덱스 1을 주면 결과는 다음과 같습니다.

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

마지막 예제의 형식은 잊어 버리십시오. 이 사이트에서 HTML 코드를 복사하고 붙여 넣는 간단한 작업은 비명을 지르고 머리카락을 뽑아 낼만큼 끔찍합니다. 더 이상 시간을 낭비하고 싶지 않습니다!


0을 조금 더 잘 처리하는 함수로 :

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


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

편집 : NaN 오류를 방지하기 위해 n 번째 자식 선택기에 괄호가 추가되었습니다. 안녕하세요.

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

문제의 예 :

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

다음은 내 unittest에서 가져온 몇 가지 예입니다.

$("<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>");

편집 : 이제 모든 부정적인 표시를 우아하게 처리합니다.


내 간단한 플러그인 사용 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));
        }
    };*

지금 :

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

또는 :

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

나열된 솔루션이 작동하지 않거나 지나치게 복잡하다는 것을 알았습니다. 추가 할 방향을 결정하기 만하면됩니다. 다음은 jQuery에 대해 OOP 방식으로 작성된 간단한 것입니다.

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

간단한 구문으로 위의 내용을 간단히 사용할 수 있습니다.

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

현재 드래그 앤 드롭을 통해 수많은 데이터를 이동하는 비주얼 편집기 프로젝트에서 이것을 사용하고 있습니다. 모든 것이 잘 작동합니다.


편집 : 위의 솔루션 http://codepen.io/ashblue/full/ktwbe로 재생할 수있는 라이브 대화 형 CodePen 데모를 추가했습니다 .


//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 );

이 작업을 많이해야하는 경우 작은 함수로 래핑 할 수 있습니다.

​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

해당 임시 ID가 염려되는 경우 마지막 단계를 추가하여 제거 할 수 있습니다.

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


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

            }
        };

Use .insertAfter():

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

You could always use 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.

참고URL : https://stackoverflow.com/questions/3562493/jquery-insert-div-as-certain-index

반응형