jQuery divas 특정 인덱스로 삽입
내가 가지고 있다고 가정해 보겠습니다.
<div id="controller">
<div id="first">1</div>
<div id="second>2</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번째 자식 선택기에 괄호를 추가했습니다.@hof나윌리
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>");
다음은 제 유니트 테스트에서 가져온 몇 가지 예입니다.
$("<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>");
편집: 이제 모든 네거티브 인디즈를 우아하게 처리합니다.
나열된 솔루션이 작동하지 않거나 지나치게 복잡하다는 것을 발견했습니다.당신이 해야 할 일은 당신이 달려오는 방향을 결정하는 것입니다.여기 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 라이브 데모를 추가했습니다.
간단한 플러그인 사용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 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 );
$('<div class="new">').insertAfter($('div.first'));
이 작업을 많이 해야 할 경우 작은 기능으로 포장할 수 있습니다.
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가 우려되는 경우 마지막 단계를 추가하여 제거할 수 있습니다.
편집: 0명의 자녀의 경우를 처리할 수 있도록 업데이트되었으며, n > 현재 div의 수를 지정했습니다.
저한테는 이게 제일 잘 어울리는데요.
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);
}
}
};
항상 prepend('#div')를 사용할 수 있습니다.
전과가 있는
$(document).ready(function(){
$('#first').prepend('<div id="new">New</div>');
});
"#first" 앞에 "#new"를 붙이게 됩니다. 그것이 당신이 원하는 것인지 확실하지 않습니다.
언급URL : https://stackoverflow.com/questions/3562493/jquery-insert-div-as-certain-index
'itsource' 카테고리의 다른 글
각도 js의 확인란 선택에 따라 div를 표시/숨기는 방법 (0) | 2023.10.04 |
---|---|
목록에서 임의로 MYSQL 삽입 (0) | 2023.10.04 |
XML에서 요소와 노드의 차이점은 무엇입니까? (0) | 2023.09.24 |
봄에 추상적="true"가 의미하는 바는 무엇입니까? (0) | 2023.09.24 |
C에서 64비트 변수 선언 (0) | 2023.09.24 |