问题
I have a html structure like this/
<li id="1"></li>
<li id="2"></li>
<li id="3"></li>
<li id="comment-box"></li>
now i wanna prepend
<li id="4"></li>
before comment-box.
i am submitting a form from the comment box and once its a success i wanna do the prepend.
回答1:
Use before():
$('#comment-box').before('<li id="4"></li>')
回答2:
Wouldn't this make more sense?:
$('ul#comments_container').prepend('<li id="4"></li>');
or
$('<li id="4"></li>').hide().prependTo('Ul#comments_container').slideDown("slow");
This would allow you to add it to the beginning of a ul list to put it at the end of the list just use 'append' rather than 'prepend' or 'appendTo' also works.
回答3:
It is uncommon to have a sequential id attached to elements but a likely case would be inserting at a specific index of a unknown length of matching elements.
If you know how many items are in the list then you can use nth-child or :eq to directly access the item without needing to couple your markup class names or id's into the jQuery selector.
$('li:nth-child(3)')
selects the third <li>
while $('li:eq(3)')
selects the fourth because :eq is zero based.
In your case my preference would be the following
$('li:last').prepend('<li>Fourth item</li>');
Here is a fiddle
回答4:
If you strictly want to use the .prepend(), the following will help you:
// this gives you a list with all matching elements
var elementsList = $("li");
// this refers to an element at required index and wraps it into a jQuery object
var elementAtIndex = $(elementsList[your index]);
// and finally apply change
elementAtIndex.prepend("<li id=\"4\"></li>");
OR
The same, using .eq(), which will be more elegant after you got the main idea. .eq allows you to refer at particular index.
var elementAtIndex= $("li").eq(your index);
elementAtIndex.prepend("<li id=\"4\"></li>");
And finally we came to the final short variant:
$("li").eq(index).prepend("<li id=\"4\"></li>");
来源:https://stackoverflow.com/questions/4202215/jquery-prepend-before-an-element