Категории HTML не отображаются

Я работаю с навигационным меню, которое строится в зависимости от данных, которые у меня есть в виде массива словарей. И у меня есть проблемы после GET, PARSE и SORT данных из массива. Я хочу создать HTML из цикла jQuery. В консоли я увидел, что появились все элементы HTML:

Категории HTML не отображаются

Однако я не видел, чтобы они появились на моей странице.

Мой код:

var mokData = [
{ mainCategory: "Technical", subCategory: "Material", id: 'UPDT-1-1', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Technical", subCategory: "Material", id: 'UPDT-1-2', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0  },
{ mainCategory: "Technical", subCategory: "Tool", id: 'UPDT-1-3', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0  },
{ mainCategory: "Organizational", subCategory: "Tool", id: 'UPDT-4-1', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0  },
{ mainCategory: "Organizational", subCategory: "Tool", id: 'UPDT-3-2', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0  },
{ mainCategory: "Organizational", subCategory: "Tool", id: 'UPDT-11-1', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0  },
{ mainCategory: "Organizational", subCategory: "Tool", id: 'UPDT-12-11', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Organizational", subCategory: "Tool", id: 'UPDT-12-11', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Organizational", subCategory: "Equipment", id: 'UPDT-12-13', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Equipment", id: 'UPDT-12-17', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Equipment", id: 'UPDT-2-11', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Equipment", id: 'UPDT-1-1', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Equipment", id: 'UPDT-122-121', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Equipment", id: 'UPDT-122-111', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Material", id: 'UPDT-122-111', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Other", subCategory: "Material", id: 'UPDT-122-111', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Other", subCategory: "Material", id: 'UPDT-122-111', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Other", subCategory: "Tool", id: 'UPDT-1-11', name: 'Brakedown of line', clicked: 0 }
];

var parseCategorys = [...mokData.reduce((c, { mainCategory, subCategory }) => {
if (!c.has(mainCategory)) c.set(mainCategory, { mainCategory, subCategory: [] });
c.get(mainCategory).subCategory.push(subCategory);
return c;
}, new Map()).values()];


$(document).ready(function () {
$('.category_list .category_item[category = "all"]').addClass('ct_item-active');

$('.category_item').click(function () {
    var catProduct = $(this).attr('category');
    console.info(catProduct);
    
    
    $.each(parseCategorys, function (i, data) {
        if (catProduct === data.mainCategory) {
            var uniqueNames = [];
            $.each(data.subCategory, function (i, el) {
                if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
            });

            $.each(uniqueNames, function (i, data) {
                console.info(data);
                var subCategoryBuild = '<div class = "product-item" category = "' + data + '"><div class = "categoryLink"><a href = "#' + data + '">' + data +'</a></div></div>';
                console.info(subCategoryBuild);
                $('.products-list').append(subCategoryBuild);
            });

           
        }

    });

    
    $('.category_item').removeClass('ct_item-active');
    $(this).addClass('ct_item-active');

    $('.product-item').css('transform', 'scale(0)');
    function hideProduct() {
        $('.product-item').hide();
    } setTimeout(hideProduct, 400);

    function showProduct() {
        $('.product-item[category = "' + catProduct + '"]').show();
        $('.product-item[category = "' + catProduct + '"]').css('transform', 'scale(1)');
    } setTimeout(showProduct, 400);
});
});

function creatingNavigationList() {
$.each(parseCategorys, function (i, data) {
    var categoryBuild = '<a href = "#" class = "category_item" category = "' + data.mainCategory + '">' + data.mainCategory + '</a>';
    $('.cteatinMainCategory').append(categoryBuild);
});
}

creatingNavigationList()
.wrap {
    max-width: 1100px;
    width: 90%;
    margin: auto;
}

.wrap > h1 {
    color: #494B4D;
    font-weight: 400;
    display: flex;
    flex-direction: column;
    text-align: center;
    margin: 15px 0px;
}

.wrap > h1:after {
    content: '';
    width: 100%;
    height: 1px;
    background: #C7C7C7;
    margin: 20px 0;
}

.store-wrapper {
    display: flex;
    flex-wrap: wrap;
}

.category_list {
    display: flex;
    flex-direction: column;
    width: 30%;
}

.category_list .category_item {
    display: block;
    width: 100%;
    padding: 15px 0;
    margin-bottom: 20px;
    background: #E84C3D;
    text-align: center;
    text-decoration: none;
    color: #fff;
}

.category_list .ct_item-active {
    background: #2D3E50;
}

.products-list {
    width: 70%;
    display: flex;
    flex-wrap: wrap;
}


.products-list .product-item {
    width: 35%;
    margin-left: 3%;
    margin-bottom: 25px;
    box-shadow: 0px 0px 6px 0px rgba(0,0,0,0.22);
    display: flex;
    flex-direction: column;
    align-items: center;
    align-self: flex-start;
    transition: all .4s;
}

.products-list .product-item img {
    width: 100%;
}

.products-list .product-item a {
    display: block;
    width: 100%;
    padding: 8px 0;
    background: #2D3E50;
    color: #fff;
    text-align: center;
    text-decoration: none;
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <div class = "wrap">
            <div class = "store-wrapper">
                <div class = "category_list">
                    <div class = "cteatinMainCategory"></div>
                </div>
                <div class = "container2">
                    <div class = "section2">
                        <div class = "scrollable-content content">
                            <section class = "products-list">
                                <div id = "creatingSubcat"></div>
                            </section>
                        </div>
                    </div>
                </div>
            </div>
        </div>

Как видите, в консоли у меня есть HTML-элементы, но они не отображаются на странице.

Это не работает из файла JS, но если я вручную помещу код ниже на страницу, он будет работать:

<div class = "product-item" category = "Material"><div class = "categoryLink"><a href = "#Material">Material</a></div></div>
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
0
64
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Кажется, в вашем javascript действительно много ошибок. Внутри вашей функции onclick на category_item.

Ваши функции hideProduct и showProduct вызываются по щелчку, в результате чего подкатегории отображаются сразу после того, как скрыты. Кроме того, вы устанавливаете масштаб всех .product-item равным 0, поэтому ширина div равна 0, поэтому они не могут отображаться.

На заметку: если вы используете функции show() и hide(), вам не следует добавлять изменение масштаба, чтобы скрыть или показать элементы. Кроме того, вы должны подумать о том, чтобы заполнить свой HTML один раз, а не по щелчку, если это возможно, потому что то, как вы это делаете, теперь бесконечно добавляет все больше и больше узлов в ваш HTML.

var mokData = [
{ mainCategory: "Technical", subCategory: "Material", id: 'UPDT-1-1', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Technical", subCategory: "Material", id: 'UPDT-1-2', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0  },
{ mainCategory: "Technical", subCategory: "Tool", id: 'UPDT-1-3', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0  },
{ mainCategory: "Organizational", subCategory: "Tool", id: 'UPDT-4-1', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0  },
{ mainCategory: "Organizational", subCategory: "Tool", id: 'UPDT-3-2', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0  },
{ mainCategory: "Organizational", subCategory: "Tool", id: 'UPDT-11-1', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0  },
{ mainCategory: "Organizational", subCategory: "Tool", id: 'UPDT-12-11', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Organizational", subCategory: "Tool", id: 'UPDT-12-11', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Organizational", subCategory: "Equipment", id: 'UPDT-12-13', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Equipment", id: 'UPDT-12-17', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Equipment", id: 'UPDT-2-11', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Equipment", id: 'UPDT-1-1', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Equipment", id: 'UPDT-122-121', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Equipment", id: 'UPDT-122-111', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Operator", subCategory: "Material", id: 'UPDT-122-111', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Other", subCategory: "Material", id: 'UPDT-122-111', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Other", subCategory: "Material", id: 'UPDT-122-111', name: 'Brakedown of machine Brakedown of machine Brakedown of machine', clicked: 0 },
{ mainCategory: "Other", subCategory: "Tool", id: 'UPDT-1-11', name: 'Brakedown of line', clicked: 0 }
];

var parseCategorys = [...mokData.reduce((c, { mainCategory, subCategory }) => {
if (!c.has(mainCategory)) c.set(mainCategory, { mainCategory, subCategory: [] });
c.get(mainCategory).subCategory.push(subCategory);
return c;
}, new Map()).values()];


$(document).ready(function () {
$('.category_list .category_item[category = "all"]').addClass('ct_item-active');

$('.category_item').click(function () {
    var catProduct = $(this).attr('category');
    //console.info(catProduct);
    
    
    $.each(parseCategorys, function (i, data) {
        if (catProduct === data.mainCategory) {
            var uniqueNames = [];
            $.each(data.subCategory, function (i, el) {
                if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
            });

            $.each(uniqueNames, function (i, data) {
                //console.info(data);
                var subCategoryBuild = '<div class = "product-item" category = "' + data + '"><div class = "categoryLink"><a href = "#' + data + '">' + data +'</a></div></div>';
                //console.info(subCategoryBuild);
                $('.products-list').append(subCategoryBuild);
            });

           
        }

    });

    
    $('.category_item').removeClass('ct_item-active');
    $(this).addClass('ct_item-active');

    //$('.product-item').css('transform', 'scale(0)');
    function hideProduct() {
        //console.info("hide");
        $('.product-item').hide();
    };
    //setTimeout(hideProduct, 400);

    function showProduct() {
        //console.info("show");
        $('.product-item[category = "' + catProduct + '"]').show();
        $('.product-item[category = "' + catProduct + '"]').css('transform', 'scale(1)');
    };
    setTimeout(showProduct, 400);
});
});

function creatingNavigationList() {
$.each(parseCategorys, function (i, data) {
    var categoryBuild = '<a href = "#" class = "category_item" category = "' + data.mainCategory + '">' + data.mainCategory + '</a>';
    $('.cteatinMainCategory').append(categoryBuild);
});
}

creatingNavigationList()
.wrap {
    max-width: 1100px;
    width: 90%;
    margin: auto;
}

.wrap > h1 {
    color: #494B4D;
    font-weight: 400;
    display: flex;
    flex-direction: column;
    text-align: center;
    margin: 15px 0px;
}

.wrap > h1:after {
    content: '';
    width: 100%;
    height: 1px;
    background: #C7C7C7;
    margin: 20px 0;
}

.store-wrapper {
    display: flex;
    flex-wrap: wrap;
}

.category_list {
    display: flex;
    flex-direction: column;
    width: 30%;
}

.category_list .category_item {
    display: block;
    width: 100%;
    padding: 15px 0;
    margin-bottom: 20px;
    background: #E84C3D;
    text-align: center;
    text-decoration: none;
    color: #fff;
}

.category_list .ct_item-active {
    background: #2D3E50;
}

.products-list {
    width: 70%;
    display: flex;
    flex-wrap: wrap;
}


.products-list .product-item {
    width: 35%;
    margin-left: 3%;
    margin-bottom: 25px;
    box-shadow: 0px 0px 6px 0px rgba(0,0,0,0.22);
    display: flex;
    flex-direction: column;
    align-items: center;
    align-self: flex-start;
    transition: all .4s;
}

.products-list .product-item img {
    width: 100%;
}

.products-list .product-item a {
    display: block;
    width: 100%;
    padding: 8px 0;
    background: #2D3E50;
    color: #fff;
    text-align: center;
    text-decoration: none;
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <div class = "wrap">
            <div class = "store-wrapper">
                <div class = "category_list">
                    <div class = "cteatinMainCategory"></div>
                </div>
                <div class = "container2">
                    <div class = "section2">
                        <div class = "scrollable-content content">
                            <section class = "products-list">
                                <div id = "creatingSubcat"></div>
                            </section>
                        </div>
                    </div>
                </div>
            </div>
        </div>

Другие вопросы по теме