我正在尝试在菜单中显示JSON文件中的所有类别。谁能帮助我使用JavaScript代码吗?我尝试了几件事,但都没有成功。
HTML :(静态)
<ul class="cd-faq-categories" id="onderwerp">
<li><a class="selected" href="#algemeen">Test</a></li>
<li><a href="#1">Test2</a></li>
<li><a href="#2">Test3</a></li>
<li><a href="#3">Test4</a></li>
<li><a href="#4">Test5</a></li>
</ul> <!-- cd-faq-categories -->
JSON结构:
{
"id": 3,
"category": "Eten",
"question": "Vis",
"answer": "Ham",
"date": "29-11-18"
}
有人可以帮我吗?我试图在HTML标记中使用相同的名称和href,例如:
<li><a href="${category}">$c{category}</a></li>
答案 0 :(得分:1)
这是有效的解决方案:
var data =[
{
"id": 3,
"category": "Eten",
"question": "Vis",
"answer": "Ham",
"date": "29-11-18"
},
{
"id": 3,
"category": "Eten 2",
"question": "Vis",
"answer": "Ham",
"date": "29-11-18"
},
{
"id": 3,
"category": "Eten 3",
"question": "Vis",
"answer": "Ham",
"date": "29-11-18"
}
]
const liTemplate = (category) => `<a href="${category}">${category}</a>`
data.forEach(item => {
var child = document.createElement('li');
child.innerHTML = liTemplate(item.category);
document.querySelectorAll('.cd-faq-categories')[0].appendChild(child);
})
解决方案是使用Json对象。遍历所有项目,并使用简单的JS JS appendChild方法附加到DOM li元素。
答案 1 :(得分:0)
JSON file is a just a text file, so in order javascript to understand it like an obj. you must parse it. You must use JSON.parse() function.
var data = JSON.parse('{
"id": 3,
"category": "Eten",
"question": "Vis",
"answer": "Ham",
"date": "29-11-18"
},');
<li><a href="${data.category}">$c{data.category}</a></li>