【发布时间】:2019-08-29 16:09:46
【问题描述】:
我想生成一个数组,表示有序列表的结构。
列表可能类似于:
<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) {
}
}
}
【问题讨论】:
标签: javascript php jquery html