Suppose i have ul with one li as shown below
<ul class="creatures_list" style="display:block">
<li cl开发者_如何转开发ass='list_creatures'><a href="#"><b>Add Creatures</b></a></li>
</ul>
What i want is insert more li's on top of given li using jQuery example as below
<ul class="creatures_list" style="display:block">
<li class='list_creatures'><a href='#'>1</a></li>
<li class='list_creatures'><a href='#'>2</a></li>
<li class='list_creatures'><a href='#'>3</a></li>
<li class='list_creatures'><a href='#'>4</a></li>
<li class='list_creatures'><a href="#"><b>Add Creatures</b></a></li>
</ul>
I hope it is understandable. Awating
$('.creatures_list').prepend(function() {
var html;
for (var i = 1; i < 5; i++) {
html += "<li class='list_creatures'><a href='#'>" + i + "</a></li>";
}
return html;
});
var $last_child = $('.creatures_list').children('.list_creatures').last();
for(var i = 0; i < 4; i++) {
$last_child.before("<li class='list_creatures'><a href='#'>" + (i + 1) + "</a></li>");
}
Are you wanting to click the "Add Creature" link and add to the <ul>
? That's what this will do, sorry if I am not understanding the question.
Here's a demo
var liCount = $('.creatures_list').children().size();
$('.add_creature').click(function(){
$(this).before('<li><a href="##" class="list_creatures">'+liCount+++'</a></li>');
return false;
});
The below solution will increment the number correctly and keep them in ascending order:
var numCreatures = 0;
function addCreature() {
$(".creatures_list li:last").before(
"<li class='list_creatures'><a href='#'>" + ++numCreatures + "</a></li>"
);
}
You can call addCreature whenever you want, for example when someone clicks on the last <li>
:
$(".creatures_list li:last").click(addCreature);
Use http://api.jquery.com/prepend/
$('#creatures_list').prepend('<li class="list_creatures"><a href="#">1</a></li>';
精彩评论