gpt4 book ai didi

javascript - 为什么会有 NaN?

转载 作者:行者123 更新时间:2023-12-02 13:52:20 25 4
gpt4 key购买 nike

点击之前:

enter image description here

点击后:

enter image description here

$(document).ready(function () {
var output = document.getElementById("whole");
if (!navigator.geolocation) {
$("#whole").html("<p>Your brower is not supported</p>");
return;
}

function success(position) {
var lan = position.coords.latitude;
var lon = position.coords.longitude;

$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?lat=" + lan + "&lon=" + lon + "&APPID=f06e25b1205b65171ad01524870cbb01",
success: function (data) {
$("#temp").text(Math.round(data.main.temp - 273.15));
}
});
}

function error() {
output.innerHTML = "Unable to retrieve your location";
}

navigator.geolocation.getCurrentPosition(success, error);

var ce = parseInt($("#temp").text(), 10);
var fa = Math.round(ce * 1.8 + 32);

$("a").on("click", function () {
if ($(this).text() == "℃") {
$(this).html("℉");
$("#temp").text(fa);
} else {
$(this).html("℃");
$("#temp").text(ce);
}
});

});
<script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<span id="temp"></span><a id="toggle" href="javascript:void(0)">℃</a>

我想实现这个,当我点击摄氏字符时,摄氏度将变成华氏度。因为代码需要位置,所以运行代码片段会抛出错误。我不知道为什么有一个NaN.但是没有用。为什么?

最佳答案

这些变量不是全局变量,因为它们是在 ready 函数的范围内声明的。

直接使用它们的名称(不使用窗口),因为您的点击处理程序也在同一范围内。

document).ready(function () {
var ce = parseInt($("#temp").text(), 10);
var fa = Math.round(ce * 1.8 + 32);

$("a").on("click", function () {
if ($(this).text() == "℃") {
$(this).html("℉");
$("#temp").text(fa);
} else {
$(this).html("℃");
$("#temp").text(ce);
}
});
});
<小时/>

更新

问题在于,#temp 元素在运行代码时没有值,因为它是由 AJAX 调用填充的(这是异步的,稍后完成)

您应该将解析代码放在AJAX的成功回调中。

$(document).ready(function () {
var output = document.getElementById("whole");
var ce, fa;
if (!navigator.geolocation) {
$("#whole").html("<p>Your brower is not supported</p>");
return;
}

function success(position) {
var lan = position.coords.latitude;
var lon = position.coords.longitude;

$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?lat=" + lan + "&lon=" + lon + "&APPID=f06e25b1205b65171ad01524870cbb01",
success: function (data) {
ce = Math.round(data.main.temp - 273.15);
fa = Math.round(ce * 1.8 + 32);
$("#temp").text( ce );
}
});
}

function error() {
output.innerHTML = "Unable to retrieve your location";
}

navigator.geolocation.getCurrentPosition(success, error);

$("a").on("click", function () {
if ($(this).text() == "℃") {
$(this).html("℉");
$("#temp").text(fa);
} else {
$(this).html("℃");
$("#temp").text(ce);
}
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="temp"></span><a id="toggle" href="javascript:void(0)">℃</a>

关于javascript - 为什么会有 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40928169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com