gpt4 book ai didi

javascript - 如何创建反向无序列表?

转载 作者:行者123 更新时间:2023-11-27 23:49:32 24 4
gpt4 key购买 nike

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

<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/了解更多信息。

关于javascript - 如何创建反向无序列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32847131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com