-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
44 lines (40 loc) · 1.48 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
fetch('products.json')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(products => {
displayProducts(products); // 确保此函数已定义
})
.catch(error => console.error('Error loading JSON:', error));
function displayProducts() {
const productGrid = document.getElementById('productGrid');
products.forEach(product => {
const productElement = document.createElement('div');
productElement.className = 'product';
productElement.innerHTML = `
<img src="${product.image}" alt="${product.name}">
<p>${product.name}</p>
<input type="checkbox" id="product${product.id}" name="product" value="${product.id}">
`;
productGrid.appendChild(productElement);
});
}
function generateList() {
const selectedItems = document.querySelectorAll('input[name="product"]:checked');
const selectedList = document.getElementById('selectedItems');
selectedList.innerHTML = '';
selectedItems.forEach(item => {
const product = products.find(p => p.id == item.value);
const li = document.createElement('li');
li.textContent = product.name;
selectedList.appendChild(li);
});
document.getElementById('selectedList').style.display = 'block';
}
window.onload = function() {
displayProducts();
document.getElementById('generateList').addEventListener('click', generateList);
};