2020年1月 実力テスト(JavaScript, jQuery)

(ブログ記事の一覧は「こちら」)

問1

JavaScript, jQueryに関する、以下の問いについて回答しなさい。

問1-1(20点)

以下のindex.htmlがあるとします。

<html>
<head>
   <meta charset="UTF-8">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <script src="main.js"></script>
</head>

<body>
    <div id="message">こんにちは</div>
    <input type="button" id="editText" value="テキスト変更">
</body>
</html>

ボタンをクリックすると、「こんにちは」の表示が以下のテキストに切り替わるような、main.jsのプログラムを作成しなさい。

ありがとう

問1-2(20点)

以下のindex.htmlがあるとします。

<html>
<head>
   <meta charset="UTF-8">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <script src="main.js"></script>
</head>

<body>
    <div id="hoge1" class="message"></div>
    <div id="hoge2" class="message"></div>
    <input type="button" id="editTextClass" value="テキスト変更">
</body>
</html>

ボタンをクリックすると、以下のテキストが表示されるような、main.jsのプログラムを作成しなさい。

ありがとう
ありがとう

問1-3(20点)

以下のindex.htmlがあるとします。
また、index.htmlと同じディレクトリに画像ファイル「icon.png」があるとします。

<html>
<head>
   <meta charset="UTF-8">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <script src="main.js"></script>
</head>

<body>
    <img id="image"/>
    <input type="button" id="showImage" value="画像を表示">
</body>
</html>

ボタンをクリックすると、画像ファイル「icon.png」が表示されるような、main.jsのプログラムを作成しなさい。

問2

OpenWeatherMap APIを用いた、現在の天気情報をWebブラウザに表示する方法について考えます。
東京(Tokyo)の現在の天気情報を表示する例は以下になります。

index.html

<html>
<head>
   <meta charset="UTF-8">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <script src="main.js"></script>
</head>

<body>
    <h1>OpenWeatherMap API</h1>

    <p>場所:<span id="place"></span></p>

    <p>天気:<span id="weather"></span></p>
    <p><span id="description"></span></p>
    <p><img id="icon"></p>

    <p>気温:<span id="temp"></span></p>

    <p>湿度:<span id="humidity"></span>%</p>
</body>
</html>

main.js

$.ajax({
    type: "GET",
    url: "https://api.openweathermap.org/data/2.5/weather?q=Tokyo&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

}).done(function(data) {
    $("#place").html(data.name);

    var img = $("#icon");
    img.attr("src", "https://openweathermap.org/img/wn/" + data.weather[0].icon + "@2x.png");
    img.attr("alt", data.weather[0].main);

    $("#weather").html(data.weather[0].main);
    $("#description").html(data.weather[0].description);

    $("#temp").html(Math.floor((data.main.temp - 273.15) * 100) / 100);

    $("#humidity").html(data.main.humidity);

}).fail(function(data) {
    alert("error");
});


上記に関する、以下の問いについて回答しなさい。

問2-1(各10点)

「気圧」の項目を追加したい場合、index.htmlとmain.jsに追加するコードを書きなさい。
(気圧の単位は「hPa(ヘクトパスカル)」です。)

問2-2(20点)

index.htmlにボタンを3個追加して、クリックすると「Tokyo」「Osaka」「XXX(あなたの生まれた場所)」に天気情報の表示が切り替わるような仕組みになるように改造したい場合について考えます。

index.htmlは以下のようにボタンを追加していく場合、main.jsはどのように修正する必要がありますか?(他の学生に説明しても理解できるような)文章とコードで、わかりやすく説明しなさい。

 ...

<p><input type="button" value="Tokyo" onclick="callOpenWeatherMap('Tokyo')"></p>

 ...