数组:数组是一种线性数据结构,用于存储相同类型的元素集合。
复选框:复选框是一种用户界面元素,允许用户从多个选项中选择一个或多个选项。
以下是一个简单的示例,展示如何在JavaScript中使用复选框从数组中收集数据并进行筛选。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checkbox Filter</title>
</head>
<body>
<h1>Filter Data</h1>
<div id="checkboxContainer"></div>
<button onclick="filterData()">Filter</button>
<ul id="result"></ul>
<script src="script.js"></script>
</body>
</html>
const data = [
{ id: 1, name: 'Apple', category: 'Fruit' },
{ id: 2, name: 'Banana', category: 'Fruit' },
{ id: 3, name: 'Carrot', category: 'Vegetable' },
{ id: 4, name: 'Broccoli', category: 'Vegetable' }
];
function renderCheckboxes() {
const container = document.getElementById('checkboxContainer');
const categories = [...new Set(data.map(item => item.category))];
categories.forEach(category => {
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = category;
checkbox.value = category;
checkbox.name = 'category';
const label = document.createElement('label');
label.htmlFor = category;
label.appendChild(document.createTextNode(category));
container.appendChild(checkbox);
container.appendChild(label);
container.appendChild(document.createElement('br'));
});
}
function filterData() {
const checkboxes = document.querySelectorAll('input[name="category"]:checked');
const selectedCategories = Array.from(checkboxes).map(cb => cb.value);
const resultContainer = document.getElementById('result');
resultContainer.innerHTML = '';
data.forEach(item => {
if (selectedCategories.includes(item.category)) {
const li = document.createElement('li');
li.textContent = `${item.name} - ${item.category}`;
resultContainer.appendChild(li);
}
});
}
renderCheckboxes();
问题1:复选框未正确显示
问题2:筛选结果不正确
问题3:性能问题
通过以上示例和解决方案,可以有效地从数组中收集数据并使用复选框进行筛选。
领取专属 10元无门槛券
手把手带您无忧上云