2016-03-30 172 views
0

我正在通過freecodecamp進行挑戰,任務是顯示當地天氣,因此我必須獲取用戶的位置。我可以得到的位置from here但打印後,我試圖得到div的ElementById我已經打印使用JS,它給出了null作爲迴應。我想獲得關鍵值對,以便我可以與他們做東西。這裏是我的代碼:提前地理位置跟蹤getElementById不工作

<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
     <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 
 
     <title>Location Trace | freecodecamp Challanges</title> 
 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
 
    </head> 
 
    <body> 
 
     <div id="GeoResults"></div> 
 
     <script> 
 
     $.getJSON("http://ip-api.com/json/?callback=?", function(data) { 
 
      var table_body = ""; 
 
      var count = 0; 
 
      $.each(data, function(k, v) { 
 
\t \t \t \t //JSON.stringify(j); // '{"name":"binchen"}' 
 
\t \t \t \t 
 
\t \t \t \t table_body += '<div id=Coun_'+count+'>'+v+'</div>'; 
 
\t \t \t \t 
 
       //table_body += "<tr><td id='FC_"+count+"'>" + k + "</td><td><b id='SC_"+count+"'>" + v + "</b></td></tr>"; 
 
       count++; 
 
      }); 
 
      $("#GeoResults").html(table_body); 
 
     }); 
 
     </script> 
 
     <script> 
 
\t \t \t var x = document.getElementById('Coun_1') /*= 'Dooone!!!'*/; 
 
\t \t \t console.log(x); 
 
     </script> 
 
    </body> 
 
</html>

謝謝!

+3

您要添加使用異步API的那些元素,所以當的getElementById叫這些元素都沒有添加到DOM –

+0

感謝您的快速回復阿倫,你能不能幫我通過詳細闡述關於Async的內容。我從哪說起呢? –

+0

關於異步http://stackoverflow.com/questions/3393751/what-does-asynchronous-means-in-ajax – GuRu

回答

0

<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
     <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 
 
     <title>Location Trace | freecodecamp Challanges</title> 
 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
 
    </head> 
 
    <body> 
 
     <div id="GeoResults"></div> 
 
     <script> 
 
     $.getJSON("http://ip-api.com/json/?callback=?", function(data) { 
 
      var table_body = ""; 
 
      var count = 0; 
 
      $.each(data, function(k, v) { 
 
\t \t \t \t //JSON.stringify(j); // '{"name":"binchen"}' 
 
\t \t \t \t 
 
\t \t \t \t table_body += '<div id=Coun_'+count+'>'+v+'</div>'; 
 
\t \t \t \t 
 
       //table_body += "<tr><td id='FC_"+count+"'>" + k + "</td><td><b id='SC_"+count+"'>" + v + "</b></td></tr>"; 
 
       count++; 
 
      }); 
 
      $("#GeoResults").html(table_body); 
 
      var x = document.getElementById('Coun_1').innerHTML; /*= 'Dooone!!!'*/; 
 
\t \t \t console.log(x); 
 
     }); 
 
     </script> 
 
    </body> 
 
</html>