为什么 toggleClass()
不能在 $('p')
上工作,该 $('p')
应该在华氏温度和摄氏温度之间切换,然后返回华氏温度等等用户想要多少次?
代码链接:http://codepen.io/duel_drawer8/pen/bpoozL
如果你看不到链接,我的完整代码:
//Our ID key for weather app
var appID = "&APPID=f74316dbe7442f12d602b1cae1a5172b";
var city;
var state;
var fahrenheit = "&units=imperial";
var temp;
//using a geo-location API to get city and state info of current user
$.getJSON('http://ip-api.com/json/?callback=?', function(data) {
city = data.city;
state = data.regionName;
getWeather(city, state);
});
//using weather API and outputting results into our HTML
function getWeather(city, state) {
var api = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + state + "" + fahrenheit + "" + appID;
$.ajax({
url: api,
dataType: 'json',
success: function(data) {
temp = data.main.temp;
$('h3').text(city + "," + state);
$('p').html(temp + '° F');
}
});
}
$('p').on('click', function(){
$('p').text(changeTemp(temp));
$('p').toggleClass(changeTemp(temp));
});
function changeTemp(temp){
var cel = (temp - 32) * 5/9;
return cel;
};
最佳答案
向 p 标记添加一个类,以决定是否应在下次点击时插入摄氏度或华氏度。
然后在每次点击时切换类别。
由于您将温度作为全局变量,因此无需将其传递给函数。
创建不同的函数来添加华氏温度或计算摄氏温度。
$('p').on('click', function(){
$('p').toggleClass('celcius');
$('p').toggleClass('fahrenheit');
if ($(this).hasClass('celcius')) {
$('p').text(setFahrenheit());
return;
}
$('p').text(setCelcius());
});
function setCelcius(){
var cel = (temp - 32) * 5/9;
return cel + "° C";
};
function setFahrenheit(){
return temp + "° F";
};
或者另一种方法——也许更简洁的方法:
- 计算 ajax 成功中的两个临时值并将其存储在一个对象中
- 将数据属性添加到 p 标签以决定接下来显示哪个值
- 点击 - 根据数据属性决定显示哪个值并切换数据属性
关于javascript - 单击时如何使用 toggleClass 在我的 $ ('p' ) 标签上在华氏温度和摄氏温度之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36370772/