如何创建反向无序列表?

How to create reversed unordered lists?

我正在尝试获取一个无序列表以倒序显示其项目。换句话说,得到这个:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

显示:

我尝试 jQuery 这个答案:jQuery reversing the order of child elements

但是,由于某种原因,它对我不起作用。 (我把它放在一个 .html 文件中,我也尝试使用 <script src="script.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>

var list = $('ul');
var listItems = list.children('li');
list.append(listItems.get().reverse());

</script>

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

另外,那个答案是4年前的,所以我想知道现在是否有更好的解决方案?

您的脚本应在 DOM(文档对象模型)完全加载后执行。 尝试用

替换您的脚本
$(document).ready(function () {
    var list = $('ul');
    var listItems = list.children('li');
    list.append(listItems.get().reverse()); 
});

您可以在此处阅读更多内容:https://learn.jquery.com/using-jquery-core/document-ready/ 了解更多信息。