如何在JQuery中通过循环追加新的列表项。每次用户单击该按钮时,都会附加一个显示正确索引的新项目。
这是我的代码示例:
$('#append').click(function() {
$('ul#myList > li').each(function(i) {
var content = "<li>" + "Item" + (1+i) + "</li>";
$(this).append(content);
});
});
输出应该像
Item 1
Item 2
Item 3
and so on
答案 0 :(得分:0)
找到总长度并将该值分配给变量然后使用此代码
$('#append').click(function() {
var contentLength = $('ul#myList > li').length;
var content = "<li>" + "Item" + (contentLength+1) + "</li>";
$('ul#myList').append(content);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="append">Add More</button>
<ul id="myList">
<li>Item1</li>
</ul>
以下是前置代码
$('#prepend').click(function() {
var contentLength = $('ul#myList > li').length;
var content = "<li>" + "Item" + (contentLength+1) + "</li>";
$('ul#myList').prepend(content);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="prepend">Add More</button>
<ul id="myList">
<li>Item1</li>
</ul>
答案 1 :(得分:0)
$('#append').click(function() {
$("#myList").append(" <li>Item " + ($('#myList > li').length + 1) + "</li>");
});
答案 2 :(得分:0)
$('#append').click(function(e) {
e.preventDefault();
$('ul#myList').append(function() {
return "<li>" + "Item " + ($('ul#myList > li').length + 1) + "</li>";
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="myList">
<li>Item 1</li>
</ul>
<button id="append" type="button">Append</button>
&#13;
答案 3 :(得分:0)
试试这个:
<ul id="addlist">
<li>item 0</li>
</ul>
<div class="clickme">
Click me to add li
</div>
$('.clickme').click(function() {
var findlist=$('ul#addlist > li').length;
$('<li> item '+findlist+'</li>').appendTo('#addlist');
});