如何使用 Jquery 在列表的第一个位置附加一个列表项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12032521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append a listitem in first position of list using Jquery
提问by Ramprasad
How to append a listitem in first position of list using Jquery?
如何使用 Jquery 在列表的第一个位置附加一个列表项?
<ul id="mylist">
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
</ul>
is it possible to append a list item before first <li>
with jquery. I try to $('#mylist li:eq(1)').before("<li></li>")
. But it not works?
是否可以在第一次<li>
使用 jquery之前附加列表项。我尝试$('#mylist li:eq(1)').before("<li></li>")
。但它不起作用?
回答by zackdever
$('#mylist').prepend('<li></li>')
回答by undefined
You are selecting the second li
element, try this:
您正在选择第二个li
元素,试试这个:
$('#mylist li:eq(0)').before("<li>first</li>");
//or $('#mylist li:first')...
or you can use prepend
method.
或者你可以使用prepend
方法。
回答by Smit
This snippet will solve the problem. Or go to the linkto learn more.
这个片段将解决这个问题。或转到链接以了解更多信息。
$('#mylist').prepend('<li>New Item</li>');
//use jQuery's prepend method.
$('button').on('click',function(){
$('#mylist').prepend('<li>New Item 1 added</li>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<ul id="mylist">
<li>First Item</li>
<li>Second Item</li>
<li>Third Item</li>
<li>Fourth Item</li>
</ul>
<button> click to add first li</button>
</body>
</html>