【发布时间】:2017-11-28 21:01:15
【问题描述】:
我的切换按钮逻辑(<script> 标签下的最后一个代码块)似乎只在一个方向上工作。具体来说,温度变量temp 以摄氏度到达这部分代码。单击按钮后,一切都成功转换为华氏温度,但随后按钮停止工作。请注意,我尝试了使用闭包的替代设计,将所有内容嵌入到 updateTemp 函数中,每次单击时更改按钮的 id,并取消$(document).ready 下的前两个变量。这是一团糟,仍然没有提供我正在寻找的切换功能。想法?
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Bootstrap -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- CSS -->
<!-- JS/JQ -->
<script>
$(document).ready(function () {
var tempType = 0;
var temp = 0;
var coords = {
lat: 0,
lon: 0
};
// retrieve and set user's latitude and longitude coordinates
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
coords.lon = position.coords.longitude;
coords.lat = position.coords.latitude;
// AJAX called here b/c getCurrentPosition is asynchronous
sendAJAX(coords);
});
} else {
alert("Sorry, I couldn't locate you. Here's the weather elsewhere.");
coords.lon = 48.8566;
coords.lat = 2.3522;
sendAJAX(coords);
}
// AJAX request and settings wrapped in fxn for ease of calling within if/else
function sendAJAX (coords) {
// enumerate AJAX request settings & pass in coordinate settings
var ajaxOptions = {
crossDomain:true,
dataType:"json",
url:"https://fcc-weather-api.glitch.me/api/current?",
data: {
lon:coords.lon,
lat:coords.lat
},
method:"GET"
};
// attached .done() fxn calls used here, as they rely on the JSON file returned by the AJAX request
$.ajax(ajaxOptions).done(updateCity).done(updateIcon).done(updateDesc).done(updateTemp).done(updateHumid).done(updateWind);
}
// update weather icon on page
function updateCity (json) {
var cityHTML = "";
cityHTML += json.name + ", " + json.sys.country;
$("#city").html(cityHTML);
}
// update weather icon on page
function updateIcon (json) {
var iconHTML = "";
iconHTML += "<img src='" + json.weather[0].icon + "'";
iconHTML += "alt='weather icon'>";
$("#icon").html(iconHTML);
}
// update description of weather on page
function updateDesc (json) {
var descHTML = "";
var desc = json.weather[0].main;
descHTML += desc;
$("#descript").html(descHTML);
changeImage(desc);
}
// update temperature
function updateTemp (json) {
var tempHTML = "";
// the 0x in front of the character code matters, no truncation allowed despite what some docs might seem to suggest
temp = Math.round(json.main.temp);
var degree = String.fromCharCode(0x2103);
tempHTML += temp + degree;
$("#temp").html(tempHTML);
}
// update humidity
function updateHumid (json) {
var humidHTML = "";
var percent = String.fromCharCode(0x0025);
humidHTML += json.main.humidity + percent;
$("#humidity").html(humidHTML);
}
// update wind speed
function updateWind (json) {
var windHTML = "";
windHTML += json.wind.speed + " knots";
$("#wind").html(windHTML);
}
// change background image
function changeImage (desc) {
if (desc.match(/Clear/)) {
$("body").css("background-image", "url(img/clear.jpg)");
} else if (desc.match(/Rain/)) {
$("body").css("background-image", "url(img/rain.jpg)");
} else if (desc.match(/Haze/)) {
$("body").css("background-image", "url(img/haze.jpg)");
} else if (desc.match(/Clouds/)) {
$("body").css("background-image", "url(img/cloudy.jpg)");
} else if (desc.match(/Snow/)) {
$("body").css("background-image", "url(img/snow.jpg)");
} else {
$("body").css("background-image", "url(img/default.jpg)");
}
}
// toggle button logic
if (tempType == "0") {
$("#convert").on("click", function () {
var fahrenheit = Math.round((9/5)*(temp) + 32);
var tempFarHTML = "";
var degree = String.fromCharCode(0x2109);
tempFarHTML += fahrenheit + degree;
$("#temp").html(tempFarHTML);
$("#convert").html("Convert to Celsius");
tempType == "1";
});
} else {
$("#convert").on("click", function () {
var celsius = temp;
var tempCelsiusHTML = "";
var degree = String.fromCharCode(0x2103);
tempCelsiusHTML += celsius + degree;
$("#temp").html(tempCelsiusHTML);
$("#convert").html("Convert to Celsius");
tempType == "0";
});
}
});
</script>
<title>Local Weather</title>
</head>
<body>
<div class="container">
<div class="row text-center">
<div id="page-title" class="col-md-12">
The Local Weather
</div>
</div>
<div class="row text-center">
<div id="city" class="col-md-12">
City
</div>
</div>
<div class="row text-center">
<h2>Current Conditions</h2>
<div id="icon" class="col-md-12 img-responsive">
Icon
</div>
<div id="descript" class="col-md-12">
Desc
</div>
</div>
<div class="row text-center">
<div class="col-md-4">
<h2>Temperature</h2>
</div>
<div class="col-md-4">
<h2>Humidity</h2>
</div>
<div class="col-md-4">
<h2>Wind</h2>
</div>
</div>
<div class="row text-center">
<div id="temp" class="col-md-4">
Temp
</div>
<div id="humidity" class="col-md-4">
Humid
</div>
<div id="wind" class="col-md-4">
Wind
</div>
</div>
<div class="row text-center">
<div id="temp" class="col-md-4">
<button id="convert" class="btn btn-default">Convert to Fahrenheit</button>
</div>
</div>
</div>
</body>
</html>
【问题讨论】:
-
您有一个重复的 id ("temp"),这会影响您的代码功能。
-
思考 - 是否有任何控制台错误?当您放置断点并单步调试时,切换位置之间会发生什么不同?
-
我最近学到的一些技巧也帮助我清理了我的代码。不要使用 html id 来识别元素,而是使用数据属性
data-el="temp"这可以让您将 html/css 与 js 完全分开。此外,在您的 js 中,在顶部定义 html 元素,例如var tempElement = '[data-el="temp"]'这使得将来进行更新变得容易,而且您不会重复代码。最后,考虑使用 let 来代替 var;这是 ES6 语法,适用于所有更新的浏览器,但不适用于旧浏览器,因此如果您需要支持旧浏览器,则需要进行转译。
标签: javascript jquery