2017-08-29 16 views
1

所以我一直在製作一個天氣應用程序最近。 我測試了我的代碼,並且當前天氣的溫度和國家以及描述不被顯示。我認爲這個問題在我的html地理位置函數後開始。我覺得這個功能無法通過天氣數據解析。沒有數據顯示在我的天氣應用程序的網頁

我的代碼是在這裏樓下:

$(document).ready(function(){ 

    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(showPosition); 
    } else { 
     x.innerHTML = "Geolocation is not supported by this browser."; 
    } 


    function showPosition(position) { 
var lat = "lat= " + position.coords.latitude; 
var lon = "lon= " + position.coords.longitude; 
getWeather(lat,lon); 
    } 

    function getWeather(lat,lon){ 
var urlstring = "https://fcc-weather-api.glitch.me/api/current?" + lat + "&" + lon; 
$.ajax({ 
    url : urlstring, 
    dataType : "jsonP", 
    success : function(data){ 
     var temp = data.main.temp; 
     var desc = data.weather[0].description; 
     var country = data.sys.country; 
     $("#desc").html(desc); 
     $("#temp").html(temp); 
    } 
}) 
    } 

    var ctof = $("#c/f").click(function(){ 
    var cel = Math.round((temp - 32) * 5/9); 
    var faren = Math.round((temp * 9/5) + 32); 
    if(ctof == true){ 
     $("#temp").html(faren); 
     } 
     else{ 
     $("#temp").html(cel); 
     } 
     }) 
    }); 

我甚至包括我的HTML代碼只是爲了便於參考

<!DOCTYPE html> 
<html> 
<head><title>Web App</title></head> 
<body> 
<div class="container"> 
    <div class="row"> 
    <header class="col-xs-12 text-center"> 
     <h1>Free Code Camp </h1> 
     <h1>Weather App</h1> 
    </header> 

    <div class="col-xs-8 col-xs-offset-2"> 
     <div class="text-center status"> 
     <p><span id="city"></span> <span id="country"></span></p> 
     <p><span id="temp"><button id="#c/f">C/F</button></span></p> 
     <p id="desc"></p> 
     </div> 
    <div class ="info"> 
<div class="develop">Developed by = Shumaila Bi Shaikh</div> 
<div class="langs">Created by: HTML,CSS,ANGULARJS</div> 
</div> 

<script src="Weather.js"></script> 

+0

這個作品在小提琴等。請參閱https://jsfiddle.net/bokav0z8/1/問題可能是您的HTML結構。 – Luka

+0

@Luka是的,你是對的。而按鈕**#c/f **? – gaetanoM

回答

0

你嘗試console.log(desc)或你的另一件數據?我懷疑你得到你所需要的數組,但你要這些陣列直接添加到您的html,這將無法正常工作......

線路是這樣的:

$("#desc").html(desc); 
    $("#temp").html(temp); 

這將除非你傳遞有效的html字符串,例如<p>Hello</p>,否則不起作用,但在這種情況下,你正在傳遞數組。您需要確定您希望如何實際顯示數據,然後將其傳遞到您的.html()調用中。

根據您的數據結構,看起來是這樣的

let descString = ""; 
desc.forEach(value => descString += "<p>" + value.something + "</p>") 
$("#desc").html(descString) 
0

你的問題是在這條線:

var ctof = $("#c/f").click(function() { 

當你需要選擇具有在CSS符號使用的字符元素你需要在它們前加一個\\。欲瞭解更多詳情,請參閱docs

因此,你需要寫:

var ctof = $("\\#c\\/f").click(function(){ 

第二個問題是在這一行:

<p><span id="temp"><button id="#c/f">C/F</button></span></p> 

當你得到data.main.temp您覆蓋,因此刪除按鈕。因此,行更改爲:

<p><span id="temp"></span><button id="#c/f">C/F</button></p> 

爲了能夠在Chrome中,你需要啓用它的地理位置顯示在此answer

fiddle

相關問題