【问题标题】:How do I make ordered list using javascript?如何使用javascript制作有序列表?
【发布时间】:2011-01-19 05:22:24
【问题描述】:

假设我有这个

<ol>
  <li>V1 One</li>
  <li>V1 Two</li>
  <li>V1 Three</li>
  <li>V1 Four</li>
</ol>`

我想使用 .js 而不是使用LI 标签来制作有序列表。 我在想js。代码可以替换第一个 V1 并将其称为 1.,替换第二个 V1 并将其称为两个等等,换句话说,计算有多少个 V1 并将它们替换为有序列表。

或者可能是这样的

<ol>
  <li>i++ V1 One</li>
  <li>i++ V1 Two</li>
  <li>i++ V1 Three</li>
  <li>i++ V1 Four</li>
</ol>

其中i++会从1开始每次递增

是的,我知道 LI 提供有序列表!

【问题讨论】:

  • 换一种说法,你要操作的数据是从哪里来的?

标签: javascript list numbered


【解决方案1】:

也许您想遍历&lt;ol&gt; 的孩子并操纵他们的innerHTML

// Get the <ol> object from the DOM
var chillun = document.getElementById("yourOL").childNodes;

// Loop through the children of the <ol>
for(i=0;i<chillun.length;i++) {
  // Test that the node is indeed an <li>
  if(chillun[i].nodeName=='LI') {
    // Change this line to manipulate the text however you need
    chillun[i].innerHTML = i;
  }
}

【讨论】:

    【解决方案2】:

    你可以有一个空的div,用javascript在div里面输入innerHTML

    function listdown(){
      var startlist = "<ol>";
      var endlist = "</ol>";
      *use a for loop to enter the <LI>, this way, you can do much more with each item*
      document.getElementById("emptydiv").innerHTML = startlist + LI list + endlist;
    }
    

    编辑

    尽管如此,JQuery 仍然是最好的选择

    【讨论】:

      【解决方案3】:

      我建议你学习(使用)一个 javascript 框架来完成这个。它将迅速加快您的 javascript 开发。 Jquery 目前非常流行,我认为您也应该使用它。 Stackoverflow 已经有一个使用 Jquery 描述你想要什么的主题 => Generating an unordered list with jQuery

      【讨论】:

      • 此外,jQuery 模板插件非常适合将 HTML 排除在 JavaScript 之外。
      【解决方案4】:

      你可以这样做:

      let ol = document.querySelector('ol');
      let i = 1;
      ol.querySelectorAll('li').forEach(function(li) {
          li.textContent = (i++) + ' ' + li.textContent;
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-14
        相关资源
        最近更新 更多