-2

yahoo から API 経由で天気を取得したい。関数は まで起動しhtmlます。alertfunction の 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 + '&deg; ' + weather.units.temp + '<br /><span>' + weather.currently + '</span></p>';
                html += '<a href="' + weather.link + '">View Forecast &raquo;</a>';

                $("#weather").html(html);
            },
            error: function (error) {
                $("#weather").html('<p>' + error + '</p>');
            }
        });
    });
</script>

アラートが機能するようになりました

しかし、このアラートでは機能しません:

<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 + '&deg; ' + weather.units.temp + '<br /><span>' + weather.currently + '</span></p>';
                html += '<a href="' + weather.link + '">View Forecast &raquo;</a>';

                $("#weather").html(html);
            },
            error: function (error) {
                $("#weather").html('<p>' + error + '</p>');
            }
        });
    });
</script>

これは私のhtmlコードです:

<div id="weather"></div>

htmlエラーがあります。お願い助けて 。

4

4 に答える 4

5

初期化も宣言もしないhtmlため、この行は追加できません。

   html += '<p>' + weather.temp + '&deg; ' + ...

html +=に変更できますvar html =

2 番目のコードは、「機能する」場合でも、varグローバルにする html 変数を明示的に宣言していない (キーワードがない) ことに注意してください。

于 2013-06-17T14:36:06.177 に答える
0

簡単な天気 APIを試してみませんか?

これは小さなjQueryの天気の例です: http://jsbin.com/isukam/1

助けが必要な場合はお知らせください。

開示: 私はこの API を所有しています。

于 2013-06-17T20:50:45.233 に答える