Рекурсивная функция JavaScript для вложенного содержимого преждевременно генерирует закрывающий тег - PullRequest
0 голосов
/ 14 декабря 2018

Я пытаюсь обработать массив JavaScript, содержащий различные уровни объектов, в контент HTML, содержащий уровни и подуровни.

Для этого я генерирую код HTML, который затем помещаю в отдельный массив.

Я проверяю свойство "подразделы" и, если оно существует, я снова вызываю функцию.

Однако после вызова функции я вставляю заключительный закрывающий тег в массив для обозначениячто текущий раздел был полностью сгенерирован, однако закрывающий тег был помещен в массив ДО вызова функции, что означает преждевременное закрытие каждого.

Если кто-то может помочь, это было бы здорово, спасибо!

Вот 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);
            }

Большое спасибо!

1 Ответ

0 голосов
/ 14 декабря 2018

Ваша функция выглядит хорошо.Проблема в том, что вы передаете массив newContent в html(), а не строку html.

Попробуйте сначала присоединить массив к:*

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...