如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:13:30  来源:igfitidea点击:

How to append a listitem in first position of list using Jquery

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 lielement, try this:

您正在选择第二个li元素,试试这个:

$('#mylist li:eq(0)').before("<li>first</li>");
//or $('#mylist li:first')...

or you can use prependmethod.

或者你可以使用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>