2016-08-20 5 views
0

私はユーザーが摂氏または華氏で気温と気温を確認できるアプリを作成しています。しかし、温度をクリックしたときに2つのユニットタイプを切り替えるときに問題があります。 This is私のデモへのリンク。Javascript Toggle HTML

そして、ここに私のJavascriptのコードは次のとおりです。

if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(function(position) { 
    $.getJSON("https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&units=imperial&appid=a62849f462c6573114f32a691f5d3c3f", function(json) { 
     var all = JSON.stringify(json); 
     var weather = JSON.stringify(json.weather[0]["description"]); 
     weather = weather.slice(1, -1); 
     var tempFahrenheit = JSON.stringify(json.main.temp); 
     var tempCelsius = JSON.stringify(json.main.temp * 2); 
     $("#weather").html(weather); 
     $("#temp").html(Math.floor(tempFahrenheit) + " &deg;<span id='units'>F</span>"); 

     $("#units").on('click', function() { 
     if ($(this).text() == "F") { 
      $("#temp").html(Math.floor(tempCelsius) + " &deg;<span id='units'>C</span>"); 
     } else { 
      $("#temp").html(Math.floor(tempFahrenheit) + " &deg;<span id='units'>F</span>"); 
     } 
     }); 

    }); 
    }); 
} 

答えて

5

あなたは#TEMPのdiv要素のHTMLコンテンツを交換するときは、ユニットのイベントハンドラを失うだけでなくDIV。代わりにイベント委任を使用してください。 bodyタグにイベントを割り当てますが、#units divのイベントを待ち受けます。

更新コード:

$("body").on('click', '#units', function() { 
    if ($(this).text() == "F") { 
     $("#temp").html(Math.floor(tempCelsius) + " &deg;<span id='units'>C</span>"); 
    } else { 
     $("#temp").html(Math.floor(tempFahrenheit) + " &deg;<span id='units'>F</span>"); 
    } 
    }); 

あなたCodepenの仕事フォーク:https://codepen.io/anon/pen/AXzYzR?editors=0010

+0

パーフェクト、ありがとう! –