衍生出来的想法……👉看这个页面
<style>
table {
text-align: center; /* 表格内容居中 */
}
</style>
<div class="container">
<table>
<thead>
<tr>
<th>设备编号</th>
<th>购买价格 (元)</th>
<th>购买时间</th>
<th>卖出时间</th>
<th>卖出价格 (元)</th>
<th>购买到卖出天数</th>
<th>每日均价 (元)</th>
<th>盈利/亏损 (元)</th>
</tr>
</thead>
<tbody id="deviceTableBody">
<!-- 初始设备记录(示例) -->
<tr>
<td>1</td>
<td class="price">2000</td>
<td class="purchaseDate">2023-01-01</td>
<td class="sellDate">2024-01-01</td>
<td class="sellPrice">2500</td>
<td class="days">0</td>
<td class="averagePrice">0.00</td>
<td class="profitLoss">0.00</td>
</tr>
<tr>
<td>2</td>
<td class="price">1500</td>
<td class="purchaseDate">2022-11-01</td>
<td class="sellDate">2023-11-01</td>
<td class="sellPrice">1400</td>
<td class="days">0</td>
<td class="averagePrice">0.00</td>
<td class="profitLoss">0.00</td>
</tr>
</tbody>
</table>
<div class="result" id="result"></div>
</div>
<script>
// 更新每一行的数据
function updateRow(row) {
var price = parseFloat(row.querySelector('.price').textContent);
var sellPrice = parseFloat(row.querySelector('.sellPrice').textContent);
var purchaseDate = new Date(row.querySelector('.purchaseDate').textContent);
var sellDate = new Date(row.querySelector('.sellDate').textContent);
// 检查数据是否有效
if (isNaN(price) || isNaN(sellPrice) || isNaN(purchaseDate.getTime()) || isNaN(sellDate.getTime())) {
return; // 如果数据无效,不进行计算
}
// 计算从购买日期到卖出日期的天数
var timeDifference = sellDate - purchaseDate;
var days = Math.floor(timeDifference / (1000 * 60 * 60 * 24)); // 转换为天数
// 更新购买到卖出天数
row.querySelector('.days').textContent = days;
// 如果天数为负,显示错误信息
if (days <= 0) {
row.querySelector('.averagePrice').textContent = "日期无效";
row.querySelector('.profitLoss').textContent = "日期无效";
return;
}
// 计算每日均价
var averagePrice = (price / days).toFixed(2);
// 更新每日均价
row.querySelector('.averagePrice').textContent = averagePrice;
// 计算盈利/亏损
var profitLoss = (sellPrice - price).toFixed(2);
// 判断盈利或亏损
var profitLossText = profitLoss >= 0 ? `盈利 ${profitLoss}元` : `亏损 ${Math.abs(profitLoss)}元`;
// 更新盈利/亏损
row.querySelector('.profitLoss').textContent = profitLossText;
}
// 获取所有的设备行并进行计算
function calculateAll() {
var rows = document.querySelectorAll('#deviceTableBody tr');
rows.forEach(function(row) {
updateRow(row);
});
}
// 初始化计算
window.onload = function() {
calculateAll();
}
</script>