我想通过雅虎的API获取天气.功能直到html.我alert在功能之前放了html.什么时候它html显示警报给我.但是当它html不起作用之后.它显示html有错误.问题是什么?
<script type="text/javascript">
$(document).ready(function () {
$.simpleWeather({
zipcode: '',
woeid: '@Html.DisplayFor(modelItem => item.zipcode)',
location: '',
unit: 'c',
success: function (weather) {
//html = '<h2>' + weather.city + ', ' + weather.region + '</h2>';
//html += '<img style="float:left;" width="125px" src="' + weather.image + '">';
alert("hi");
html += '<p>' + weather.temp + '° ' + weather.units.temp + '<br /><span>' + weather.currently + '</span></p>';
html += '<a href="' + weather.link + '">View Forecast »</a>';
$("#weather").html(html);
},
error: function (error) {
$("#weather").html('<p>' + error + '</p>');
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
现在警报工作
但在此警报不起作用:
<script type="text/javascript">
$(document).ready(function () {
$.simpleWeather({
zipcode: '',
woeid: '@Html.DisplayFor(modelItem => item.zipcode)',
location: '',
unit: 'c',
success: function (weather) {
html = '<h2>' + weather.city + ', ' + weather.region + '</h2>';
html += '<img style="float:left;" width="125px" src="' + weather.image + '">';
alert("hi");
html += '<p>' + weather.temp + '° ' + weather.units.temp + '<br /><span>' + weather.currently + '</span></p>';
html += '<a href="' + weather.link + '">View Forecast »</a>';
$("#weather").html(html);
},
error: function (error) {
$("#weather").html('<p>' + error + '</p>');
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
这是我的HTML代码:
<div id="weather"></div>
Run Code Online (Sandbox Code Playgroud)
html有错误.请帮帮我 .
您没有初始化也没有声明,html因此该行无法附加到它:
html += '<p>' + weather.temp + '° ' + ...
Run Code Online (Sandbox Code Playgroud)
你可以html +=改为var html =.
请注意,第二个代码,即使它"有效",仍然没有明确声明html变量(var关键字缺失),这使得它变得全局.