?JavaScript
实现一个商品订单表格,功能要求:1.该表格用于展示商品订单信息;2.奇数行背景色为白色、字
体黑色,偶数行背景色为灰色、字体白色;3.商品数据自行准备,应使用数组、对象数据结构进行
存储。表格字段应包括:序号、订单号、商品名称、数量、单价、总价。
?
?
<!DOCTYPE html>
<html>
<head>
<title>商品订单表格</title>
<style>
/* 表格样式 */
table {
width: 100%;
border-collapse: collapse;
}
th, td {
text-align: center;
padding: 8px;
}
th {
background-color: #333;
color: white;
}
.even-row {
background-color: #f2f2f2;
color: black;
}
.odd-row {
background-color: #666;
color: white;
}
</style>
</head>
<body>
<div id="table-container"></div>
<script>
//商品订单数据
var orders = [
{ orderNumber: "20231234", productName: "商品A", quantity: 2, price: 10, total: 20 },
{ orderNumber: "20231235", productName: "商品B", quantity: 3, price: 15, total: 45 },
{ orderNumber: "20231236", productName: "商品C", quantity: 1, price: 8, total: 8 },
{ orderNumber: "20231237", productName: "商品D", quantity: 5, price: 12, total: 60 },
{ orderNumber: "20231238", productName: "商品E", quantity: 1, price: 8, total: 8 },
{ orderNumber: "20231239", productName: "商品F", quantity: 5, price: 12, total: 60 }
];
// 获取表格容器元素
var tableContainer = document.getElementById("table-container");
// 创建表格元素
var table = document.createElement("table");
table.classList.add("order-table");
// 创建表头行
var thead = document.createElement("thead");
var headerRow = document.createElement("tr");
var headers = ["序号", "订单号", "商品名称", "数量", "单价", "总价"];
headers.forEach(function(header) {
var th = document.createElement("th");
th.textContent = header;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// 创建表格内容
var tbody = document.createElement("tbody");
orders.forEach(function(order, index) {
var row = document.createElement("tr");
// 设置奇偶行的背景色和字体颜色
if (index % 2 === 0) {
row.classList.add("even-row");
} else {
row.classList.add("odd-row");
}
// 创建单元格
var cells = [
index + 1,
order.orderNumber,
order.productName,
order.quantity,
order.price,
order.total
];
cells.forEach(function(cellData) {
var cell = document.createElement("td");
cell.textContent = cellData;
row.appendChild(cell);
});
tbody.appendChild(row);
});
table.appendChild(tbody);
// 将表格添加到容器中
tableContainer.appendChild(table);
</script>
</body>
</html>