選擇基準幣種、輸入金額,自動查詢匯率表,動態生成「目標幣種、兌換金額、匯率」表格。
<form name="messageForm">
<div class="refitem">
基準幣種:<select onchange="outputRst()" id="sMoney">
<option>請選擇..</option>
<option>美元</option>
<option>人民幣</option>
<option>英鎊</option>
<option>日元</option>
</select>
金額<input type="text" id="amount" onchange="outputRst()" />
</div>
<br/><br/>
<table id="tbRst" border="1">
<tr><td>幣種</td><td>兌換金額</td><td>匯率</td></tr>
</table>
</form>
<script>
// 匯率基準:以美元為中介
const rate = {
美元: { 人民幣: 6.5781, 英鎊: 0.6943, 日元: 119.53, 美元: 1 }
};
const allCurrencies = '美元,人民幣,英鎊,日元';
const tbRst = document.getElementById('tbRst');
const sel = document.getElementById('sMoney');
function outputRst() {
// 清空舊行
while (tbRst.rows.length > 1) tbRst.deleteRow(-1);
if (sel.selectedIndex === 0) return; // 未選擇
const base = sel.options[sel.selectedIndex].text; // 基準幣種
const amount = parseFloat(document.getElementById('amount').value) || 0;
// 目標幣種 = 所有幣種 - 基準幣種
const targets = allCurrencies.split(',').filter(c => c !== base);
targets.forEach(t => {
let r;
if (base === '美元') r = rate.美元[t]; // 直接查表
else r = 1 / rate.美元[base] * rate.美元[t]; // 交叉匯率計算
const row = tbRst.insertRow();
row.insertCell().textContent = t;
row.insertCell().textContent = (r * amount).toFixed(2);
row.insertCell().textContent = r.toFixed(4);
});
}
</script>
| 步驟 | 關鍵代碼 |
|---|---|
| 清空舊數據 | `while (tbRst.rows.length > 1) tbRst.deleteRow(-1);` |
| 獲取基準幣種與金額 | `sel.options[sel.selectedIndex].text`、`parseFloat(...)` |
| 計算目標幣種列表 | `allCurrencies.split(',').filter(c => c !== base)` |
| 匯率換算 | 直接查表 或 `1/rate[base]*rate[target]` (交叉匯率) |
| 動態生成行 | `insertRow()` + `insertCell()` + `textContent` |
**純前端即可實現完整匯率換算工具,核心是「以單一基準幣種為中介」計算交叉匯率。**