javascript 如何使用javascript制作有序列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4731995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make ordered list using javascript?
提问by Alex
Lets say I have this
可以说我有这个
<ol>
<li>V1 One</li>
<li>V1 Two</li>
<li>V1 Three</li>
<li>V1 Four</li>
</ol>`
I want to make an ordered list using .js instead of using LItags.
I was thinking the js. code could replace first V1 and call it 1. , replace second V1 and call it two and so on, in other words counting how many V1s there are and replacing them with ordered list.
我想使用 .js 而不是使用LI标签来制作一个有序列表。我在想js。代码可以替换第一个 V1 并称其为 1. ,替换第二个 V1 并称其为二等,换句话说,计算有多少个 V1 并用有序列表替换它们。
Or maybe something like this
或者像这样
<ol>
<li>i++ V1 One</li>
<li>i++ V1 Two</li>
<li>i++ V1 Three</li>
<li>i++ V1 Four</li>
</ol>
Where i++ will be increased every time starting from 1
i++ 每次从 1 开始都会增加
Yes, I know LI provide ordered list!
是的,我知道 LI 提供有序列表!
回答by Ben
Perhaps you want to loop through the children of <ol>and manipulate their innerHTML?
也许您想遍历的孩子<ol>并操纵他们的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;
}
}
回答by robobooga
You can have an empty div, and use javascript to enter the innerHTML inside the div
你可以有一个空的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;
}
EDIT
编辑
Nonetheless, JQuery is still the best option
尽管如此,JQuery 仍然是最好的选择
回答by Alfred
I would advise you to learn(use) a javascript framework to accomplish this. It will speed up your javascript development rapidly. Jquery is very popular at the moment and I think you should also use that. Stackoverflow allready has a topic using Jquery describing what you want => Generating an unordered list with jQuery
我建议你学习(使用)一个 javascript 框架来完成这个。它将快速加速您的 javascript 开发。Jquery 目前非常流行,我认为您也应该使用它。Stackoverflow 已经有一个使用 Jquery 描述你想要什么的主题 =>使用 jQuery 生成一个无序列表
回答by aznafro
you could do something like this:
你可以做这样的事情:
let ol = document.querySelector('ol');
let i = 1;
ol.querySelectorAll('li').forEach(function(li) {
li.textContent = (i++) + ' ' + li.textContent;
});

