簡體   English   中英

HTML5地理位置結果移出了我的網頁-如何阻止它?

[英]HTML5 geolocaton result moves off my webpage - how to stop that?

我正在嘗試更熟悉HTML5。 我是一位經驗豐富的程序員,但是是一名JavaScript新手。 我已經為getCurrentPosition編寫了一些代碼(位置固定后會導致異步回調)。 這是代碼(我已經測試了該平台上對地理定位的支持並獲得了積極的回應):

 function tryGeo() {
     document.write("asking for location <br>");
     try {
       navigator.geolocation.getCurrentPosition(savePos);
   } catch (e) {
     document.write("Excpn in asking for location <br>");
   }
     document.write("have asked for location <br>");
}

該代碼運行時,將彈出權限請求窗口或對話框。 我授予權限。 這是在MacOS 10.6.7的Firefox 3.6.8上。

一段時間后,將發生savePos()的回調(當位置已知時):

function savePos(pos) {
   lat = pos.coords.latitude;
   lon = pos.coords.longitude;
   document.write("have got location lat " +lat+ ", lon " +lon+ " <br>");
}

我遇到的問題是document.write()移至新的空白頁。 相反,我想在發出getCurrentPosition()請求時將文本添加到正在渲染的頁面中。 我怎樣才能做到這一點?

我可能在犯一些瑣碎的初學者錯誤-請讓我知道。

另外,將鏈接到“為經驗豐富的程序員學習javascript”資源。 解凍

彼得

這就是document.write工作方式:

在不調用document.open()情況下寫入已加載的document.open()將自動執行document.open調用。

document.open

如果目標中存在文檔,則此方法將其清除。

上面那個注釋的例子:

// In this example, the document contents are 
// overwritten as the document 
// is reinitialized on open(). 
document.write("<html><p>remove me</p></html>"); 
document.open(); 
// document is empty.

最簡單的方法是在頁面上已有一個元素,然后更新該元素的內容。 因此,您會有一些HTML:

<p id="you-are-here"></p>

然后在回調中:

document.getElementById('you-are-here').innerHTML = "have got location lat " + lat + ", lon " + lon;

所以,是的,您平凡的初學者的錯誤是在已經加載的document.write上使用document.write

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM