http://codepen.io/PaxBlueRibbon/pen/wWJWXj
我正在尝试自学 JavaScript,但是这个华氏度/摄氏度开关没有任何作用。我这样设置开关:
$(document).ready(function getPosition() {
if (document.getElementById('myonoffswitch').checked) {
var unit = "Fahrenheit";
} else {
var unit = "Celsius";
}
并在 JS 中设置条件,如下所示
var tempKelvin = json.main.temp;
var tempFahrenheit = tempKelvin * 1.8 - 459.67;
var tempCelsius = tempKelvin - 273.15;
if (unit == "Fahrenheit") {
$(".temp").html(Math.round(tempFahrenheit) + " Degrees " + unit);
}
if (unit == "Celsius") {
$(".temp").html(Math.round(tempCelsius) + " Degrees " + unit);
}
华氏度有效,如果我将变量更改为其他值,它将停止工作,但我无法让它显示摄氏度。
最佳答案
因为您正在使用 jQuery。
// you should add event listener.
$('#myonoffswitch').change(function(){
// and change "unit" every time checkbox is changed
unit = $(this).prop('checked') ? 'Fahrenheit' : 'Celsius';
// change html here
});
您可以在页面加载时调用此事件
$('#myonoffswitch').change();
关于javascript - 我的 javascript 复选框没有执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38316249/