首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用HTML按第一行的第一个字母以外的行/元素对列表进行排序

使用HTML按第一行的第一个字母以外的行/元素对列表进行排序
EN

Stack Overflow用户
提问于 2019-05-08 16:06:17
回答 1查看 23关注 0票数 0

我现在才开始学习超文本标记语言,我偶然发现了如何对w3schools上的列表进行排序[链接-> https://www.w3schools.com/howto/howto_js_sort_list.asp ]

使用该链接中的代码,我替换了所有< li>元素(奥斯陆、斯德哥尔摩、赫尔辛基等)包括以下三个方面:

Jessica< br>

London< br>

1975年

Aaron< br>

Tokyo< br>

1962年

Peter< br>

新的York< br>

1958

现在,当我单击“排序”时,列表当然会按预期排序,按第一行的第一个字母排序,如下所示:

Aaron

东京

1962年

杰西卡

伦敦

1975年

彼得

纽约

1958

我想要的是再添加两个排序按钮;一个按第二行排序,另一个按第三行排序。我做了一个图表来更好地描述我所说的:https://i.imgur.com/uiPEYqs.png

这有可能吗?让我知道,谢谢。

EN

Stack Overflow用户

发布于 2019-05-08 17:19:01

修改后的示例

使用sortList('2')sortList('3')进行基于第二行和第三行的排序

您可以将以下代码复制粘贴到此url:https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_list

其他URL:

代码语言:javascript
运行
复制
<!DOCTYPE html>
<html>
<title>Sort a HTML List Alphabetically</title>
<body>

<p>Click the button to sort the list alphabetically:</p>
<button onclick="sortList('1')">Sort</button>

<div id="id01">
    <ul class="group">
        <li class="1">Aaron</li>
        <li class="2">Tokyo</li>
        <li class="3">2012</li>
    </ul>
    <ul class="group">
        <li class="1">Jessica</li>
        <li class="2">London</li>
        <li class="3">2015</li>
    </ul>
    <ul class="group">
        <li class="1">Peter</li>
        <li class="2">New York</li>
        <li class="3">2008</li>
    </ul>
</div>

<script>
function sortList(sort_class_name) {
  /*
    sort_class_name - 1,2,3
  */
  var list, i, switching, b, shouldSwitch;
  list = document.getElementById("id01");
  switching = true;
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // start by saying: no switching is done:
    switching = false;
    b = list.getElementsByClassName(sort_class_name);
    console.log(b);
    // Loop through all list-items:
    for (i = 0; i < (b.length - 1); i++) {
      // start by saying there should be no switching:
      shouldSwitch = false;
      /* check if the next item should
      switch place with the current item: */
      if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
        /* if next item is alphabetically
        lower than current item, mark as a switch
        and break the loop: */
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark the switch as done: */
      b[i].parentNode.parentNode.insertBefore(b[i + 1].parentNode, b[i].parentNode);
      switching = true;
    }
  }
}
</script>

</body>
</html>
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56036183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档