如何反转无序列表中列表项的顺序 [英] How to reverse the ordering of list items in an unordered list

查看:59
本文介绍了如何反转无序列表中列表项的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个无序列表,例如:

Let's say I have an unordered list, like this:

<ul id="birds">
  <li>Bald Eagle</li>
  <li>Falcon</li>
  <li>Condor</li>
  <li>Albatross</li>
  <li>Parrot</li>
</ul>

使用普通的JavaScript(不包括jQuery),我希望能够反转此列表的顺序-使其与以下预期的输出"相匹配:

With plain JavaScript (not including jQuery), I would like to be able to do reverse the order of this list - so that it matches the following expected "output":

<ul id="birds">
  <li>Parrot</li>
  <li>Albatross</li>
  <li>Condor</li>
  <li>Falcon</li>
  <li>Bald Eagle</li>
</ul>

这是我尝试编写的JavaScript,以尝试实现此目标:

This is the JavaScript I have attempted to code, to try and achieve this goal:

var birdList = document.getElementById("birds").getElementsByTagName("li");
var birdListReverse = birdList.reverse();

for(var i = 0; i < birdList.length; i++)
{
  birdList[i] = birdListReverse[i];
}

我认为以某种方式用反转"列表中的项目覆盖当前列表项目就足够了,但事实并非如此.我是否必须以某种方式操纵列表中的每个 nodeValue ?

I would think that somehow over-writing the current list items with the ones in the "reversed" list would be sufficient, but not to be. Would I have to somehow manipulate each nodeValue in the list?

我想在单击按钮时执行此操作-这很容易,它只是获得了一种反转列表的技术,该操作已使我有点受阻.

I would like to do this when a button is clicked - that is the easy part, it is just getting the technique to reverse the list that has hampered me a bit.

推荐答案

HTMLCollection只是节点的只读视图.为了操作节点,您必须使用各种DOM操作方法之一.在您的情况下,碰巧有一条捷径;您所需要做的就是以相反的顺序附加子节点.

An HTMLCollection is only a read-only view of nodes. In order to manipulate nodes, you have to use one of the various DOM manipulation methods. In your case, there happens to be a shortcut; all you need do is to append the child nodes in reverse order.

var birds = document.getElementById("birds");
var i = birds.childNodes.length;
while (i--)
  birds.appendChild(birds.childNodes[i]);

编辑:发生的情况是 appendChild 在添加节点之前从文档中删除了该节点.这有两个效果:a)避免了您必须制作节点列表的副本并在以相反的顺序附加节点之前将其删除的情况,以及b)可以逆转节点的顺序,因为它附加了最后一个子节点第一个和第一个子列表.

Edit: What's happening is that appendChild removes the node from the document before appending it. This has two effects: a) it saves you from having to make a copy of the list of nodes and removing them before appending them in reverse order, and b) it reverses the order of nodes as it goes, since it appends the last child first and the first child list.

这篇关于如何反转无序列表中列表项的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆