出于某种原因,我只能让点击事件在温度元素(id:#temp)上触发一次。转换为华氏度后,它不会转换回摄氏温度。我刚开始使用 jQuery,所以任何帮助将不胜感激。源代码如下。
HTML 源代码:
<html>
<head>
<link rel="stylesheet" href="main.css"/>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="main.js"></script>
<script type="text/javascript" async src="https://platform.twitter.com/widgets.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"></link>
</head>
<body>
<h1>Local Weather Code Camp Project</h1>
<h4>Location</h4>
<p id="location"></p>
<h4>Weather</h4>
<p id="weather"></p>
<img id="icon">
<h3 id="temp"></h3>
<p id="check"></p>
</body>
</html>
jQuery 源代码:
$(document).ready(function () {
navigator.geolocation.getCurrentPosition(function(position) {
$.getJSON('https://fcc-weather-api.glitch.me/api/current?lat=' + position.coords.latitude + '&lon=' + position.coords.longitude , function(data){
var tmpInt = 0;
$("h1").html(JSON.stringify(data));
$("#location").html(data.name);
$("#weather").html(data.weather[0].description);
$("#icon").attr("src", data.weather[0].icon);
$("#temp").html(data.main.temp + "° C");
$(document).on('click','#temp',function() {
tmpInt = data.main.temp;
tmpInt = tmpInt * 1.8 +32;
if("#temp:contains('° C')") {
$("#temp").html(tmpInt + "° F");
$("#check").html("Contains C");
}
else if("#temp:contains('° F')") {
$("#temp").html(data.main.temp + "° C");
$("#check").html("Contains F");
}
});
});
});
});
在这里工作 CodePen 。
条件始终评估为真,因此温度始终更改为 F。
使用另一个变量来记住显示的单位(C 或 F)有效......
var units = 'C';
$("#temp").on("click", function() {
tmpInt = data.main.temp;
tmpInt = tmpInt * 1.8 + 32;
if (units == 'C') {
$("#temp").html(tmpInt + "° F");
units = 'F';
} else if (units == 'F') {
$("#temp").html(data.main.temp + "° C");
units = 'C';
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句