以下是一个简单的 JavaScript 商品分类列表代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>商品分类列表</title>
</head>
<body>
<ul id="categoryList"></ul>
<script>
// 假设这是从后端获取的商品分类数据
const categories = [
{ id: 1, name: '电子产品', parent: 0 },
{ id: 2, name: '手机', parent: 1 },
{ id: 3, name: '电脑', parent: 1 },
{ id: 4, name: '家用电器', parent: 0 },
{ id: 5, name: '电视', parent: 4 },
{ id: 6, name: '冰箱', parent: 4 },
{ id: 7, name: '食品饮料', parent: 0 },
{ id: 8, name: '零食', parent: 7 },
{ id: 9, name: '饮料', parent: 7 }
];
// 构建分类列表
function buildCategoryList(categories) {
const categoryMap = {};
const rootCategories = [];
categories.forEach(category => {
categoryMap[category.id] = { ...category, children: [] };
});
categories.forEach(category => {
if (category.parent === 0) {
rootCategories.push(categoryMap[category.id]);
} else {
const parentCategory = categoryMap[category.parent];
if (parentCategory) {
parentCategory.children.push(categoryMap[category.id]);
}
}
});
return rootCategories;
}
const categoryList = buildCategoryList(categories);
// 渲染分类列表到页面
const categoryListElement = document.getElementById('categoryList');
categoryList.forEach(category => {
const li = document.createElement('li');
li.textContent = category.name;
if (category.children.length > 0) {
const subUl = document.createElement('ul');
category.children.forEach(child => {
const subLi = document.createElement('li');
subLi.textContent = child.name;
subUl.appendChild(subLi);
});
li.appendChild(subUl);
}
categoryListElement.appendChild(li);
});
</script>
</body>
</html>
基础概念: 这是一个使用 JavaScript 处理商品分类数据并在页面上展示分类列表的示例。
优势:
类型: 这是一个基于前端 JavaScript 的分类列表实现。
应用场景: 适用于电商网站、在线商城等需要对商品进行分类展示的场景。
可能遇到的问题及解决方法:
领取专属 10元无门槛券
手把手带您无忧上云