gpt4 book ai didi

javascript - 点击事件仅在第二次点击后显示数据

转载 作者:行者123 更新时间:2023-12-03 00:43:51 26 4
gpt4 key购买 nike

我正在研究 jQuery.ajax() 方法来将一段 JSON 数据存储在 var d 中。我在控制台中注意到,在首次单击按钮后,变量被存储,但直到第二次单击才会显示。有人可以详细说明这一点并提出解决方案吗?

    var d;
$(document).ready(function () {
$('#Weather').click(function () {
var requestData = $('#City').val() + ',' + $('#Country').val();
var unit = 'imperial';
var key = '..........................';
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather',
method: 'get',
data: { q: requestData, units: unit, APPID: key },
dataType: 'json',
success: function (data) {
d = data.main.temp;
}
});
if (d >= 40) {
document.getElementById("Text").value = "Value = " + d + " °";
}
else if (d < 40) {
document.getElementById("Text1").value = "Value = " + d + " °";
}
});
});

<table>
<tr>
<td>Enter City</td>
<td><input type="text" id="City" /></td>
</tr>
<tr>
<td>Enter Country</td>
<td><input type="text" id="Country" /></td>
</tr>
</table>
<button id="Weather" >Get d</button>
<input type="text" id="Text" value="T °" />
<input type="text" id="Text1" value="T °" />

这是 JSON

    "main": {
"temp": 37.38,
"pressure": 1030,
"humidity": 36,
"temp_min": 35.06,
"temp_max": 39.2
},

谢谢。

最佳答案

在 AJAX 调用之外使用 if/else,它会在发送调用后立即执行,即 d未定义,然后两个条件都失败。

因此,将 if/else 移至成功回调内,因为此时 d 的值已更新。

$('#Weather').click(function () {
var requestData = $('#City').val() + ',' + $('#Country').val();
var unit = 'imperial';
var key = '..........................';
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather',
method: 'get',
data: { q: requestData, units: unit, APPID: key },
dataType: 'json',
success: function (data) {
d = data.main.temp;
if (d >= 40) {
document.getElementById("Text").value = "Value = " + d + " °";
}
else if (d < 40) {
document.getElementById("Text1").value = "Value = " + d + " °";
}
}
});

});

关于javascript - 点击事件仅在第二次点击后显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53332850/

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