我在几周内遇到了一个问题,我无法理解。
我有一个有序列表,它是嵌套的。
<html>
<head>
<style>
OL { counter-reset: item }
LI { display: block }
LI:before { content: counters(item, ".") " "; counter-increment: item }
</style>
</head>
<body>
<ol>
<li>Number One</li>
<li>Number Two
<ol>
<li>Number Two - One</li>
<li>Number Two - Two</li>
<li>Number Two - Three</li>
</ol>
</li>
<li>Number Three
<ol>
<li>Number Three - One</li>
<li>Number Three - Two</li>
<ol>
<li>Number Three - Two - One</li>
<li>Number Three - Two - Two</li>
</ol>
</ol>
</li>
<li>Number Four</li>
</ol>
</body>
</html>
但是,我需要一种使用Javascript的方法(因为这些CSS规则不适用于TCPDF)。
所以,我无法弄清楚如何使用Javascript来实现一个函数来修改这些ol,li(嵌套元素 - 父和子)来添加编号1,2,2.1,2.2,3,3.1 ,3.1.2,3.2.2没有CSS。
我已经知道我需要使用类似的东西:
<script>
function
...
getElementById('li')
getElementsByTagName('li')
...
</script>
感谢您的帮助。
答案 0 :(得分:1)
其一,您的HTML与您的HTML不一致,有时您会将<ol>
个项目嵌入<li>
内,有时则不会。我将此归因于一个错误,并为您创建了一个递归函数,就像您总是将它们嵌套一样,您可以在下面找到它。它会更改HTML,因此您不应该有任何问题。
我所说的不一致发生在3-2-1 / 3-2-2,你关闭<li>
标签3-2,然后打开<ol>
标签,{{1}成为3-3
<ol>
&#13;
var root = document.getElementsByTagName('OL')[0];
recur(root)
function recur(element, id, index) {
id = id || "";
index = index || "";
if (element.tagName === "LI") {
id = id ? (id + "." + index) : index;
element.innerHTML = id + ". " + element.innerHTML;
}
Array.prototype.slice.call(element.children).forEach(function(el, ind) {
ind++;
recur(el, id, ind);
})
}
&#13;
li {
list-style: none;
}
&#13;