Say I have this:
<div id="controller">
<div id="first">1</div>
<div id="second>2</div>
</div>
but say I wanted to insert a new div arbitrarily based on an index I supply.
Say I gave the index to insert of 0, the result should be:
<div id="controller">
<div id="new">new</div>
<div id="first">1</div>
<div id="second">2</div>
</div>
and if I have an index to insert of 2 the result would be.
<div id="controller">
<div id="first">1</div>
<div id="second">2</div>
<div id="new">new</div>
</div>
and if I give an index of 1 the result would be:
<div id="controller">
<div id="first">1</div>
<div id="new">new</div>
<div id="second">2</div>
</div>
just forget that last example's format. The simple act of copying and pasting HTML code on this site is horrific enough to make me about scream and pull my hair out and I dont want to spend anymore time messing with it!
Как функция с немного лучшей обработкой 0:
function insertAtIndex(i) {
if(i === 0) {
$("#controller").prepend("<div>okay things</div>");
return;
}
$("#controller > div:nth-child(" + (i) + ")").after("<div>great things</div>");
}
РЕДАКТИРОВАТЬ: Добавлены круглые скобки в селектор nth-child, чтобы избежать ошибок NaN. @hofnarwillie
function insertAtIndex (i) {if (i === 0) {$ ("# controller"). prepend (" все в порядке "); возвращение; } $ ("# контроллер> div: nth-child (" + (i) + ")"). after (" великие дела "); } window.doInsert = функция () {insertAtIndex (2); }
Элемент 1 Элемент 2 Элемент 4 Элемент 5
Если вам нужно делать это часто, вы можете обернуть это небольшой функцией:
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.
Вы всегда можете использовать prepend ('# div');
ex.
$(document).ready(function(){
$('#first').prepend('<div id="new">New</div>');
});
Это поставило бы "#new" перед "#first" Не уверен, что вы этого хотите.