我有2个按钮,当点击按钮时,它应该根据相应的类别显示产品。然而,有这样一个问题,当你第二次点击按钮时,这些产品再次出现,不断重复。我希望它点击一次,到达一次,而不是每次。我如何防止这种情况?
const arr = [
{
"id": "1",
"Name": "Coke 500ml",
"Price": "80",
"Quantity": "50",
"Category": "bike"
},
{
"id": "2",
"Name": "Cake",
"Price": "150",
"Quantity": "40",
"Category": "clothing"
},
{
"id": "3",
"Name": "Beef Ribs",
"Price": "100",
"Quantity": "50",
"Category": "clothing"
},
{
"id": "4",
"Name": "Cabbage Salad",
"Price": "50",
"Quantity": "30",
"Category": "clothing"
},
{
"id": "5",
"Name": "Cake",
"Price": "150",
"Quantity": "30",
"Category": "bike"
},
{
"id": "6",
"Name": "Beef Ribs",
"Price": "100",
"Quantity": "30",
"Category": "bike"
}
];
const row = document.querySelector('.row')
function filterArrayByCategory(category) {
const a = arr.filter(el => el.Category === category);
console.log(a);
a.map(element => {
const div = document.createElement('div')
div.className = 'col-lg-4 col-md-4 col-sm-6 col-12 p-3'
div.innerHTML = `
<div class="card" style="width: 18rem; height: 100% ">
<div class="card-body">
<h5 class="card-title">${element.Name}</h5>
<p class="card-text">${element.Category}</p>
</div>
</div>
`
row.appendChild(div)
});
}
<!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>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
</head>
<body>
<button class="bk" onclick="filterArrayByCategory('bike')">bike</button>
<button class="clthng" onclick="filterArrayByCategory('clothing')">clothing</button>
<section>
<div class="container">
<div class="row">
</div>
</div>
</section>
<script src="script.js"></script>
</body>
</html>
3条答案
按热度按时间ar5n3qh51#
1:使用具有类别信息的数据集值
2:使用类
noDisplay
通过切换类方法显示/隐藏信息...qyswt5oh2#
只需添加
row.innerHTML = '';
以在单击时清除行:lsmepo6l3#
问题是因为你是在追加而不是替换
替换该行
与