嵌套内容的递归JavaScript函数过早地生成结束标记



我正在尝试将包含不同级别对象的JavaScript数组处理为包含级别和子级别的HTML内容。

为此,我生成HTML代码,然后将其推入一个单独的数组中。

我检查属性"subdives",如果它存在,我会再次调用该函数。

然而,在函数被调用后,我将最后一个结束标记推入数组,以表示当前部分已经完全生成,然而,在调用函数之前,结束标记已经推入数组,这意味着每个部分都提前关闭。

如果有人能帮忙,那就太感谢了!

这是JSFiddle。

下面是总结的JavaScript代码:

var newContent = [];
var content = [{
name: 'layer1',
content: '<p>This is where the content for layer 1 will go. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>'
},{
name: 'layer2',
content: '<p>This is where the content for layer 2 will go. Integer efficitur nulla faucibus, tempus sapien a, malesuada dui. </p>',
subsections: [{
name: 'layer2a',
content: '<p>This is where the content for layer 2a will go. Quisque faucibus sem id nibh efficitur venenatis.</p>'
]}
},{
name: 'layer3',
content: '<p>This is where the content for layer 3 will go. Etiam mi nibh, fermentum scelerisque eros condimentum, laoreet eleifend ante.</p>'
},{
name: 'layer4',
content: '<p>This is where the content for layer 4 will go. Nulla dui libero, varius id lacus in, cursus vehicula massa. Sed arcu enim, molestie nec magna ullamcorper, vehicula efficitur sapien.</p>',
subsections: [{
name: 'layer4a',
content: '<p>This is where the content for layer 4a will go. Quisque faucibus sem id nibh efficitur venenatis.</p>',
subsections: [{
name: 'layer4b',
content: '<p>This is where the content for layer 4b will go. Nam id sapien auctor, egestas nulla a, cursus odio.</p>'
}]
}]
}
]
$(document).ready(function(){
loopNestedContent(content);
$('#output').html(newContent);
})
function loopNestedContent(targContent) {
for (let i = 0; i < targContent.length; i++) {
newContent.push('<h3 id="' + targContent[i].name + '" class="trigger">' + targContent[i].name + '<span>+</span></h3>');
newContent.push('<div id="' + targContent[i].name + 'Info" class="info">');
newContent.push(targContent[i].content);
if (hasProp(targContent[i], 'subsections')) {
loopNestedContent(targContent[i].subsections);
}
newContent.push('</div>');
}
}
$(document).on('click', '#output .trigger', function() {
$('.helpInfo').css('display', 'none');
$('.trigger span').html('+');
$('#' + $(this).attr('id') + 'Info').css('display', 'block');
$(this).children('span').html('-');
})
function hasProp (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}

非常感谢!

您的函数看起来不错。问题是,您将数组newContent传递给html(),而不是一个html字符串。

尝试先使用加入阵列

$('#output').html(newContent.join('n'));

这里有一个分叉的小提琴div概述,以帮助显示结构:

https://jsfiddle.net/drnsjaob/

最新更新