我一直在做一个简单的天气应用程序项目。用户在一个输入元素中输入一个邮政编码(当点击一个按钮元素时)将对wunderground.com进行API调用。然后从JSON对象中抓取几条数据,并将其串入并插入到DOM中。jQuery .on('click')API调用问题
(function() {
var wundergroundAPI = "https://api.wunderground.com/api/3b411ca908826af8/conditions/q/";
var input = $('input');
$('#submit').on('click', function() {
var inputValue = input.val();
var weatherByZip = wundergroundAPI += inputValue += '.json';
$.getJSON(weatherByZip, function(json) {
$('#temp-f')
.text('Temperature: ' + JSON.stringify(json['current_observation']['temp_f']) + ' F');
$('#location')
.text('Location: '+ JSON.stringify(json['current_observation']['display_location']['full']));
$('#weather')
.text('Weather: ' + JSON.stringify(json['current_observation']['weather']));
input.val("");
})
});
})();
jQuery在第一个API调用中工作正常。
GET https://api.wunderground.com/api/3b411ca908826af8/conditions/q/70118.json
但是,第二个API调用没有。
GET https://api.wunderground.com/api/3b411ca908826af8/conditions/q/70118.json06840.json
这个问题似乎是在我宣布weatherByZip变量的方式:
var weatherByZip = wundergroundAPI += inputValue += '.json';
是我的本意是,weatherByZip变量将被更新(用新inputValue将加上以.json扩展名)每次调用该函数。相反,inputValue和.json会附加到先前创建的变量的末尾。
70118.json06840.json
70118.json06840.json90210.json
我该如何解决我的jQuery功能,以纠正这个问题。也就是说,每次调用函数(单击一个按钮元素)时,都会发生新的/更新的API调用?
谢谢Alain Stoffels!它工作完美。有时候我会陷入一个问题中,忽略简单的解决方案。我一直在考虑使用什么jQuery方法,而不是改变我的操作符。 – GoMagikarp