我想生成一个表示有序列表结构的数组。
列表可能类似于:
<ol class="list">
<li><p>1</p>
<ol>
<li><p>1.1</p></li>
<li><p>1.2</p></li>
<li><p>1.3</p>
<ol>
<li><p>1.3.1</p></li>
</ol>
</li>
<li><p>1.4</p></li>
</ol>
</li>
<li><p>2</p></li>
<li><p>3</p></li>
</ol>
我使用以下Javascript / Jquery函数遍历此列表(基于此答案:https://stackoverflow.com/a/18084008/11995425)
var count = 0;
var pages = [];
var parentStack = [];
var result = {};
parentStack.push(0);
function createNewLevel(obj) {
var obj = obj || $('.list');
if (obj.prop('tagName') == 'P') {
++count;
pages.push({
pId: parentStack[parentStack.length - 1],
urlStr: obj.text(), myId: count
});
}
if(obj.children().length > 0 ) {
obj.find('> li').each(function(i){
$(this).children().each(function(j){
if($(this).prop('tagName') == 'OL') {
parentStack.push(count);
}
createNewLevel($(this));
if($(this).prop('tagName') == 'OL') {
parentStack.pop();
}
});
})
}
}
createNewLevel();
这将生成一个数组:
0: Object { pId: 0, urlStr: "1", myId: 1 }
1: Object { pId: 1, urlStr: "1.1", myId: 2 }
2: Object { pId: 1, urlStr: "1.2", myId: 3 }
3: Object { pId: 1, urlStr: "1.3", myId: 4 }
4: Object { pId: 4, urlStr: "1.3.1", myId: 5 }
5: Object { pId: 1, urlStr: "1.4", myId: 6 }
6: Object { pId: 0, urlStr: "2", myId: 7 }
7: Object { pId: 0, urlStr: "3", myId: 8 }
pId引用myId作为父级。
我无法将其转换为多数组。最后,我通过ajax将此数组(json.stringify)传递给PHP。最好在运行“ createNewLevel”时生成此数组。但是也可以稍后在PHP中对其进行转换。结果应如下所示:
array(5) {
[0]=>
array(2) {
["desc"]=>
string(1) "1"
["children"]=>
array(0) {
}
}
[1]=>
array(2) {
["desc"]=>
string(1) "2"
["children"]=>
array(4) {
[0]=>
array(2) {
["desc"]=>
string(3) "2.1"
["children"]=>
array(0) {
}
}
[1]=>
array(2) {
["desc"]=>
string(3) "2.2"
["children"]=>
array(0) {
}
}
[2]=>
array(2) {
["desc"]=>
string(3) "2.3"
["children"]=>
array(3) {
[0]=>
array(2) {
["desc"]=>
string(5) "2.3.1"
["children"]=>
array(0) {
}
}
[1]=>
array(2) {
["desc"]=>
string(5) "2.3.2"
["children"]=>
array(0) {
}
}
[2]=>
array(2) {
["desc"]=>
string(5) "2.3.3"
["children"]=>
array(0) {
}
}
}
}
[3]=>
array(2) {
["desc"]=>
string(3) "2.4"
["children"]=>
array(0) {
}
}
}
}
[2]=>
array(2) {
["desc"]=>
string(1) "3"
["children"]=>
array(0) {
}
}
[3]=>
array(2) {
["desc"]=>
string(1) "4"
["children"]=>
array(0) {
}
}
[4]=>
array(2) {
["desc"]=>
string(1) "5"
["children"]=>
array(0) {
}
}
}
答案 0 :(得分:0)
您可以使用reduce
方法和递归根据您的html生成嵌套结构。如果子元素具有ol
,则可以调用generate函数,其中element参数将是该ol
元素。
function generate(element, pid = 0) {
return [...element.children].reduce((r, li) => {
const p = li.querySelector('p');
const ol = li.querySelector('ol');
const obj = {pid};
if (p) obj.text = p.textContent;
if (ol) obj.children = generate(ol, pid + 1);
r.push(obj);
return r;
}, [])
}
const result = generate(document.querySelector('.list'))
console.log(JSON.stringify(result, 0, 4))
<ol class="list">
<li><p>1</p>
<ol>
<li><p>1.1</p></li>
<li><p>1.2</p></li>
<li><p>1.3</p>
<ol>
<li><p>1.3.1</p></li>
</ol>
</li>
<li><p>1.4</p></li>
</ol>
</li>
<li><p>2</p></li>
<li><p>3</p></li>
</ol>