[英]jquery how to fill li's on top of li inside ul
Suppose i have ul with one li as shown below 假设我有一个li的ul,如下所示
<ul class="creatures_list" style="display:block">
<li class='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 我想要的是使用jQuery示例在给定的li上插入更多li,如下所示
<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>");
}
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>
: 您可以随时调用addCreature,例如,当某人单击最后一个
<li>
:
$(".creatures_list li:last").click(addCreature);
使用http://api.jquery.com/prepend/
$('#creatures_list').prepend('<li class="list_creatures"><a href="#">1</a></li>';
Are you wanting to click the "Add Creature" link and add to the <ul>
? 是否要单击“添加生物”链接并添加到
<ul>
? That's what this will do, sorry if I am not understanding the question. 这就是这样做的方法,对不起,如果我不理解这个问题。
var liCount = $('.creatures_list').children().size();
$('.add_creature').click(function(){
$(this).before('<li><a href="##" class="list_creatures">'+liCount+++'</a></li>');
return false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.