我们假设这样的HTML结构:
<div id="relevantHeadings">
<h1>First Heading</h1>
<h2>First Subheading</h2>
<div>
<!-- for clarification that the headings are not necessarily siblings -->
<h2>Second Subheading</h2>
</div>
<h1>Second Heading</h1>
<h1>Third Heading</h1>
<h1>Fourth Heading</h1>
<h2>Third Subheading</h2>
<h1>Fith Heading</h1>
</div>
编辑:标题不一定是彼此的兄弟姐妹。
我需要的是:
'menu': {
'level':[
{
'label': 'First Heading',
'level' :[
{
'label': 'First Subheading'
},
{
'label': 'Second Subheading'
}]
},
{
'label': 'Second Heading'
},
{
'label': 'Third Heading'
},
{
'label': 'Fourth Heading',
'level' :[
{
'label': 'Third Subheading'
}]
},
{
'label': 'Fith Heading'
}]
}
我的实际代码更复杂,属性多于label
和更多尺寸/等级。
到目前为止,我开始尝试了很多但是我无法弄清楚如何将子数组正确地推送到数组的一个项目中:
this.allHeadings = $('#relevantHeadings').find('h1, h2, h3, h4, h5, h6');
this.obj = {};
this.obj['level'] = [];
this.allHeadings.each(function(i) {
if($(this).is('h1')) {
thiz.obj['level'].push(this);
} else if($(this).is('h2')) {
// create and push this one into thiz.obj['level'][i-1]['level']
}
});
答案 0 :(得分:0)
我很确定这就是你想要的:
http://jsfiddle.net/Iber/a8Kgj/用于测试检查控制台。
以下是代码:
function findNodes(step, $this) {
var selector = null;
var object = {};
object['level'] = [];
if ($this) selector = $this.next('h' + step);
else selector = $("h" + step);
selector.each(function () {
var innerObject = {
label: $(this).text()
};
var nextHeading = findNodes(step + 1, $(this));
if (nextHeading.level.length > 0) {
innerObject.level = nextHeading;
}
object['level'].push(innerObject);
});
return object;
}
console.log(findNodes(1));
答案 1 :(得分:0)
好的,我明白了。这是最丑陋的代码,如果比我更聪明的人有一点时间,我很乐意,如果你要清理它并将其作为答案发布,我就可以接受它。 我确信有一种方法可以缩短它。
此代码仅适用于h1
到h3
,但您明白了这一点。
var prevObj;
var h1 = 0;
var h2 = 0;
var h3 = 0;
var buildNavigation = function(containerSel) {
var thiz = this;
this.container = $(containerSel);
this.allHeadings = $(container).find('h1, h2, h3, h4, h5, h6');
this.obj = {};
this.obj['level'] = [];
this.allHeadings.each(function(i) {
myLoop(this, i);
});
return this.obj;
}
var myLoop = function(element, index) {
var thiz = this;
this.ele = element;
this.index = index;
if($(this.ele).is('h1')) {
var innerObject = {
label: $(ele).text()
}
thiz.obj['level'].push(innerObject);
prevObj = thiz.obj['level'][h1];
h1++;
} else if($(ele).is('h2')) {
if(prevObj.level) {
} else {
prevObj['level'] = [];
}
prevObj.level.push({
label: $(ele).text()
});
prevObj2 = prevObj['level'][h2];
h2++;
} else if($(ele).is('h3')) {
if(prevObj2.level) {
} else {
prevObj2['level'] = [];
}
prevObj2.level.push({
label: $(ele).text()
});
prevObj3 = prevObj2['level'][h3];
h3++;
}
}
$(document).ready(function() {
buildNavigation('#relevantHeadings');
}