You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用TypeScript/JavaScript实现两个HTML select元素的选中值互换

问题原因及修复方案

核心错误点

  • getElementById()返回的是单个DOM元素,无需加[0]索引,你代码中所有document.getElementById("select1")[0].value、document.getElementById("select2")[0].value的写法都是错误的,相当于读取第一个option的固定值,无法获取当前选中值,也无法修改选中状态。
  • 若你未给触发按钮绑定swapCurrencies的点击事件,或是按钮放在form标签内未指定类型,会默认触发表单提交刷新页面,也会导致点击无反应。

正确实现代码

修复后的JS逻辑

let currency1 = "";
let currency2 = "";

// 缓存DOM元素,避免重复查询,性能更好
const select1 = document.getElementById("select1");
const select2 = document.getElementById("select2");

select1.addEventListener("change", () => {
  currency1 = select1.value;
});

select2.addEventListener("change", () => {
  currency2 = select2.value;
});

function swapCurrencies() {
  // 互换存储变量
  [currency1, currency2] = [currency2, currency1];
  // 互换下拉框选中值
  [select1.value, select2.value] = [select2.value, select1.value];
}

触发按钮绑定示例

你的触发按钮需要绑定点击事件才能调用互换函数,写法参考:

<button type="button" onclick="swapCurrencies()">互换币种</button>

注意button要加type="button",否则放在form标签内会默认触发表单提交,导致页面刷新,功能失效。

内容的提问来源于stack exchange,提问作者Robson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:54:03