我有问题,我必须点击两次才能在第一次单击时交换按钮文本和类。所有其他时间在第一次点击时发生变化。 我已经尝试删除单击changeUnits()函数内部,但在这种情况下,我可以更改为Celcius一次,不能再交换值。我正在分配价值和班级,因为我打算稍后在另一个API调用中使用它来检索指定单元中的天气。 有没有人看到我在做什么错了?不得不点击两次执行onclick
HTML
<button id="units" class="Fahrenheit" onclick="changeUnits();callWeather()">F</button>
的JavaScript
function changeUnits() {
if($("#units").hasClass("Fahrenheit")) {
$(".Fahrenheit").click(function() {
$(".Fahrenheit").text("C");
$(this).removeClass('Fahrenheit').addClass('Celcius');
});
}
else if($("#units").hasClass("Celcius")) {
$(".Celcius").click(function() {
$(".Celcius").text("F");
$(this).removeClass('Celcius').addClass('Fahrenheit');
});
}
}
你执行首先点击你的'changeUnits()'和在该功能你设定另一个点击监听器 - 这就是为什么你必须点击两次。删除不必要的监听器('$(“。Fahrenheit”)。click(function(){'and'$(“。Celcius”)。click(function(){'),它将按预期工作。 –