我已经设置了一个 if | 否则,如果脚本将我的项目上显示的温度从 Celcius 切换到 Ferinheit,它就可以工作了。当我单击“C”时,它会进行数字转换并将“F”附加到末尾。但是,现在当我单击“F”时,它不会切换回来,我不知道为什么。我尝试在函数外部声明变量,以防它们以某种方式被覆盖,但这也不起作用。这是 JS 代码(至少是与问题相关的部分):
num = Math.round(parseInt(arr.main.temp));
var temp = num+String.fromCharCode(176)+`<span class=\"temp\" id='ctof'>${tempValue}</span>`;
$("#temperature").html(temp)
$('#ctof').click(function () {
var currentTempUnit = tempValue;
var newTempUnit = currentTempUnit == "C" ? "F" : "C";
console.log(newTempUnit);
tempValue = newTempUnit;
if (newTempUnit == "F") {
num = Math.round(parseInt(arr.main.temp * (9/5) + 32));
var fahTemp = num+String.fromCharCode(176)+`<span class=\"temp\" id='ctof'>${tempValue}</span>`;
$("#temperature").html(fahTemp)
} else {
$("#temperature").text(temp);
}
完整代码和CSS等。codepen在这里:https ://codepen.io/chase-hippen/pen/WzqBvj?editors = 0011
当你这样做时:
$('#ctof').click(function ()...
您将该点击函数附加到当前存在的DOM 元素,其 id 为ctof
。当您稍后创建具有相同 ID 的新节点时,它不会自动选取相同的事件侦听器。
将函数分开,以便您可以在多个地方添加它,并确保在创建新节点时再次添加侦听器。
这是您的代码的编辑版本:https : //codepen.io/anon/pen/OvKVNX?editors=0011
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句