请原谅这个非常琐碎的问题,但是我刚刚开始尝试Javascript,但似乎无法弄清楚我在哪里出错了。
未捕获的ReferenceError:温度未定义
每个小技巧都将不胜感激!
$.ajax({
url: 'https://api.weather.gov/gridpoints/EWX/92,61/forecast/hourly' }).done(function(res) {
var temp = res.properties.periods[0].temperature;
});
function test () {
document.getElementById('temperature').innerHTML = temp;
}
答案 0 :(得分:0)
在脑海中使用外部脚本标签,例如<head><script type='text/javascript' src='folder/file.js'></script></head>
。在file.js
上就像$(function(){ /* put all your code in here */ });
。当然,如果您想在异步活动之后做某事,那么它一定会发生。请参阅以下内容:
//<![CDATA[
/* js/external.js */
$(function(){ // jQuery load
$.get('https://api.weather.gov/gridpoints/EWX/92,61/forecast/hourly', function(resultObj){
$('#out').html(resultObj.properties.periods[0].temperature+'° F');
});
}); // jQuery load end
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px 5px;
}
#out{
margin-top:10px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
Look in the <head> above then at the jQuery below
<div id='out'></div>
</div>
</body>
</html>
答案 1 :(得分:0)
AJAX是异步调用。每次调用函数temp
时,test
始终是未定义的。您可以通过执行以下操作来实现所需的目标:
function test() {
$.ajax({
url: 'https://api.weather.gov/gridpoints/EWX/92,61/forecast/hourly'
})
.done(function(res) {
var temp = res.properties.periods[0].temperature;
document.getElementById('temperature').innerHTML = temp;
});
}