温度单位转换器点击转换按钮无响应问题求助
温度单位转换器点击转换按钮无响应问题求助
嘿,我帮你排查了代码,发现两个关键问题导致点击转换按钮没反应:
输出单位变量赋值错误
你在JS代码里把outputUnit错误地赋值成了输入单位的元素值,这会导致输出单位永远和输入单位一致,更关键的是结合第二个问题直接引发报错。正确的赋值应该是获取输出单位下拉框的值:const outputUnit = document.getElementById("outputUnit").value;单位标识大小写不匹配
你的HTML里下拉选项的value属性是小写格式(比如celsius),但JS中conversions对象的键是首字母大写的(比如Celsius)。这就导致conversions[inputUnit]会返回undefined,后续调用undefined[outputUnit](inputTemp)时直接抛出错误,整个点击事件函数执行失败,所以按钮看起来毫无反应。你可以选择两种修正方式:
- 把HTML里所有option的value改成首字母大写(比如
Celsius) - 把JS里
conversions对象的键改成小写(更符合前端常规写法)
- 把HTML里所有option的value改成首字母大写(比如
下面是修正后的完整JS代码(采用第二种修正方式,同时修复了outputUnit的赋值问题):
document.getElementById("confirm").addEventListener("click", function () { const inputTemp = parseFloat(document.getElementById("inputTemp").value); const inputUnit = document.getElementById("inputUnit").value; // 修复:正确获取输出单位 const outputUnit = document.getElementById("outputUnit").value; const conversions = { // 键改为小写,匹配HTML里的value celsius: { fahrenheit: (temp) => temp * 9 / 5 + 32, kelvin: (temp) => temp + 273.15, celsius: (temp) => temp, }, fahrenheit: { celsius: (temp) => (temp - 32) * 5 / 9, kelvin: (temp) => (temp - 32) * 5 / 9 + 273.15, fahrenheit: (temp) => temp, }, kelvin: { celsius: (temp) => temp - 273.15, fahrenheit: (temp) => (temp - 273.15) * 9 / 5 + 32, kelvin: (temp) => temp, }, } const result = conversions[inputUnit][outputUnit](inputTemp); document.getElementById("outputTemp").textContent = String(result || 0); });
另外你提到尝试添加DOMContentLoaded事件,其实你的JS脚本已经用了defer属性,这会让脚本在DOM完全加载后再执行,所以原本不需要额外包裹。如果要加的话,记得把整个事件监听代码都放在DOMContentLoaded的回调函数里,像这样:
document.addEventListener("DOMContentLoaded", function () { document.getElementById("confirm").addEventListener("click", function () { // 这里放原本的转换逻辑 }); });
修正后点击转换按钮应该就能正常工作啦!
备注:内容来源于stack exchange,提问作者viper
相关产品推荐
相关产品推荐

