在电商平台上,商品列表的对比展示功能允许用户同时查看多个商品的详细信息,以便于做出购买决策。以下是一个简单的JavaScript代码示例,用于实现淘宝商品列表的对比展示功能。
以下是一个简单的JavaScript代码示例,用于实现商品列表的对比展示功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>商品对比</title>
<style>
.product {
border: 1px solid #ccc;
padding: 10px;
margin: 10px;
width: 200px;
}
.comparison-table {
border-collapse: collapse;
width: 100%;
}
.comparison-table th, .comparison-table td {
border: 1px solid #ccc;
padding: 10px;
}
</style>
</head>
<body>
<h1>商品对比</h1>
<div id="product-list">
<!-- 商品列表 -->
<div class="product" data-id="1">商品1</div>
<div class="product" data-id="2">商品2</div>
<div class="product" data-id="3">商品3</div>
</div>
<button onclick="compareProducts()">对比</button>
<table id="comparison-table" class="comparison-table"></table>
<script>
const products = [
{ id: 1, name: '商品1', price: 100, brand: '品牌A' },
{ id: 2, name: '商品2', price: 150, brand: '品牌B' },
{ id: 3, name: '商品3', price: 120, brand: '品牌C' }
];
function compareProducts() {
const selectedProducts = Array.from(document.querySelectorAll('.product.selected')).map(el => parseInt(el.getAttribute('data-id')));
if (selectedProducts.length < 2) {
alert('请选择至少两个商品进行对比');
return;
}
const comparisonTable = document.getElementById('comparison-table');
comparisonTable.innerHTML = `
<tr>
<th>属性</th>
${selectedProducts.map(id => `<th>商品${id}</th>`).join('')}
</tr>
`;
const firstProduct = products.find(p => p.id === selectedProducts[0]);
Object.keys(firstProduct).forEach(key => {
const row = `<tr>
<td>${key}</td>
${selectedProducts.map(id => `<td>${products.find(p => p.id === id)[key]}</td>`).join('')}
</tr>`;
comparisonTable.innerHTML += row;
});
}
document.querySelectorAll('.product').forEach(product => {
product.addEventListener('click', () => {
product.classList.toggle('selected');
});
});
</script>
</body>
</html>
问题:对比表格显示不正确。 原因:可能是由于商品ID不匹配或数据获取错误。 解决方法:确保商品ID正确,并且在生成对比表格时正确获取商品数据。
通过以上代码和解释,可以实现一个简单的商品对比功能,并解决常见的显示问题。
没有搜到相关的文章