问题描述
我已经考虑了一段时间,但无法提出可行的解决方案.我什至无法伪造代码...
I've been pondering this for a while but cannot come up with a working solution. I can't even psuedo code it...
例如,您的页面标题结构如下:
Say, for example, you have a page with a heading structure like this:
<h1>Heading level 1</h1>
<h2>Sub heading #1</h2>
<h2>Sub heading #2</h2>
<h3>Sub Sub heading</h3>
<h2>Sub heading #3</h2>
<h3>Sub Sub heading #1</h3>
<h3>Sub Sub heading #2</h3>
<h4>Sub Sub Sub heading</h4>
<h2>Sub heading #4</h2>
<h3>Sub Sub heading</h3>
使用JavaScript(任何框架都可以),如何生成这样的列表:(带有嵌套列表)
Using JavaScript (any framework is fine), how would you go about producing a list like this: (with nested lists)
<ol>
<li>Heading level 1
<ol>
<li>Sub heading #1</li>
<li>Sub heading #2
<ol>
<li>Sub Sub heading</li>
</ol>
</li>
<li>Sub heading #3
<ol>
<li>Sub Sub heading #1</li>
<li>Sub Sub heading #2
<ol>
<li>Sub Sub Sub heading (h4)</li>
</ol>
</li>
</ol>
</li>
<li>Sub heading #4
<ol>
<li>Sub Sub heading</li>
</ol>
</li>
</ol>
</li>
</ol>
每次我尝试使用某种方法开始时,结果都会变得blo肿.
Everytime I try and begin with a certain methodology it ends up getting very bloated.
该解决方案需要遍历每个标题并将其放入适当的嵌套列表中-我一直对自己重复此操作,但是我无法画出任何东西!
The solution needs to traverse each heading and put it into its appropriate nested list - I keep repeating this to myself but I can't sketch out anything!
即使您脑子里有一个方法论,但没有时间编写它,我仍然想知道!:)
Even if you have a methodology in your head but haven't got time to code it up I'd still like to know it! :)
谢谢!
推荐答案
首先,构建一棵树.伪代码(因为我不太熟练使用Javascript):
First, build a tree. Pseudocode (because I'm not fluent in Javascript):
var headings = array(...);
var treeLevels = array();
var treeRoots = array();
foreach(headings as heading) {
if(heading.level == treeLevels.length) {
/* Adjacent siblings. */
if(heading.level == 1) {
treeRoots[] = heading; // Append.
} else {
treeLevels[treeLevels.length - 2].children[] = heading; // Add child to parent element.
}
treeLevels[treeLevels.length - 1] = heading;
} else if(heading.level > treeLevels.length) {
/* Child. */
while(heading.level - 1 > treeLevels.length) {
/* Create dummy headings if needed. */
treeLevels[] = new Heading();
}
treeLevels[] = heading;
} else {
/* Child of ancestor. */
treeLevels.remove(heading.level, treeLevels.length - 1);
treeLevels[treeLevels.length - 1].children[] = heading;
treeLevels[] = heading;
}
}
接下来,我们将其横切,以建立列表.
Next, we transverse it, building the list.
function buildList(root) {
var li = new LI(root.text);
if(root.children.length) {
var subUl = new UL();
li.children[] = subUl;
foreach(root.children as child) {
subUl.children[] = buildList(child);
}
}
return li;
}
最后,将 buildList
返回的 LI
插入到每个 treeRoots
的 UL
中.
Finally, insert the LI
returned by buildList
into a UL
for each treeRoots
.
在jQuery中,您可以按如下顺序获取标头元素:
In jQuery, you can fetch header elements in order as such:
var headers = $('*').filter(function() {
return this.tagName.match(/h\d/i);
}).get();
这篇关于将标题层次结构生成为有序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!