我有一个PHP function,该PHP根据它们的类别,子类别,大子类别等生成一些博客文章的分层视图。它生成一个包含div标签及其数据属性的字符串。我想根据其属性<ul><li>
的值将这些div转换为html aria-level
。
php方法的实际输出
<div role="heading" aria-level="1">Test 1</div>
<div role="heading" aria-level="2">Test 1.1</div>
<div role="heading" aria-level="3">Test 1.1.1</div>
<div role="heading" aria-level="3">Test 1.1.2</div>
<div role="heading" aria-level="1">Test 2</div>
<div role="heading" aria-level="3">Test 2.1.1</div>
<div role="heading" aria-level="2">Test 2.2</div>
使用php / js / jquery /任何框架所需的输出
到目前为止我取得了什么成就?
function buildRec(nodes, elm, lv) {
var node;
// filter
do {
node = nodes.shift();
} while(node && !(/^h[123456]$/i.test(node.tagName)));
// process the next node
if(node) {
var ul, li, cnt;
var curLv = parseInt(node.tagName.substring(1));
if(curLv == lv) { // same level append an il
cnt = 0;
} else if(curLv < lv) { // walk up then append il
cnt = 0;
do {
elm = elm.parentNode.parentNode;
cnt--;
} while(cnt > (curLv - lv));
} else if(curLv > lv) { // create children then append il
cnt = 0;
do {
li = elm.lastChild;
if(li == null)
li = elm.appendChild(document.createElement("li"));
elm = li.appendChild(document.createElement("ul"));
cnt++;
} while(cnt < (curLv - lv));
}
li = elm.appendChild(document.createElement("li"));
// replace the next line with archor tags or whatever you want
li.innerHTML = node.innerHTML;
// recursive call
buildRec(nodes, elm, lv + cnt);
}
}
// example usage
var all = document.getElementById("content").getElementsByTagName("*");
var nodes = [];
for(var i = all.length; i--; nodes.unshift(all[i]));
var result = document.createElement("ul");
buildRec(nodes, result, 1);
document.getElementById("outp").appendChild(result);
<div id="outp">
</div>
<div id="content">
<h1>Test 1</h1>
<h2>Test 1.1</h2>
<h3>Test 1.1.1</h3>
<h3>Test 1.1.2</h3>
<h1>Test 2</h1>
<h3>Test 2.1.1</h3>
<h2>Test 2.2</h2>
<p></p>
</div>
要解决的问题吗?
如您在上面看到的,它使用标题标签进行排序。但不幸的是,我的类别层次结构不仅限于6级。它可能会增长。因此,我希望JS / Jquery /任何框架根据其属性值将一些标签转换为ul / li结构。如果需要从后端进行任何更改,我可以将这些属性/标记从PHP更改为任何属性/标记。如果可以从PHP方面轻松实现,那么也欢迎一些示例代码片段。将上述div标签视为单个字符串输入。 :)