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-кода на этом сайте достаточно ужасен, чтобы заставить меня закричать и вытащить мои волосы, и я не хочу тратить больше времени на общение с ним!
Ответы
Ответ 1
Как функция с немного лучшей обработкой 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: добавлена скобка в селекторе nth-child, чтобы избежать ошибок 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>
Ответ 2
У меня была аналогичная проблема. К сожалению, ни один из решений не работал у меня. Поэтому я закодировал это так:
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>");
Вот несколько примеров, взятых из моих 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>");
Изменить: Теперь он обрабатывает все отрицательные индексы изящно.
Ответ 3
Используйте мой простой плагин 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)
Ответ 4
Я нашел, что перечисленные решения не работали или были чрезмерно сложными. Все, что вам нужно сделать, это определить направление, из которого вы добавляете. Вот что-то простое написано в 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;
};
Вы можете просто использовать приведенное выше с помощью простого синтаксиса.
$('#myListItem').insertIndex(2);
В настоящее время это используется в проекте визуального редактора, перемещая тонны данных с помощью перетаскивания. Все отлично работает.
Изменить: я добавил интерактивную демо-версию CodePen, где вы можете играть с вышеупомянутым решением http://codepen.io/ashblue/full/ktwbe
Ответ 5
//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 );
Ответ 6
Если вам нужно сделать это много, вы можете обернуть его в небольшой функции:
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
Если вас беспокоит этот временный идентификатор, вы можете добавить последний шаг для его удаления.
Изменить: Обновлено для обработки случаев с нулевыми дочерними элементами и указано n > текущее количество div.
Ответ 7
Это лучше для меня,
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);
}
}
};
Ответ 8
Вы всегда можете использовать prepend ('# div');
ех.
$(document).ready(function(){
$('#first').prepend('<div id="new">New</div>');
});
Это поставит "#new" перед "#first" Не уверен, что это то, что вы хотите.