![](/img/trans.png)
[英]JQuery / Javascript: Function not calling within document.ready
[英]Calling a JavaScript Function on document.ready
文檔加載完成后,我正在嘗試使用JavaScript在HTML中設置一個段落元素的值,但它似乎無法正常工作。
從帶有紅色下划線的圖片中,我已經指出:
1)我已經包含了Google CDN的jQuery庫。
2)我已經將我的.ts文件與HTML文件“鏈接”(不確定正確的詞是什么)。
3)我已經將段落元素的id設置為“ filler”
<!DOCTYPE HTML>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> <!-- Makes me host Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script> <!-- Not sure if I'll need this -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://use.fontawesome.com/4c5e04f914.js"></script>
<script src="http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID={178e8d4180edebe4e2c02fcad75b72fd}"></script>
<script src="../js/script.ts"></script>
</head>
<body>
<div class="jumbotron text-center">
<h1 id="filler">Weather Wizard</h1>
<p>Finding your local weather!</p>
<!-- Your current location is: -->
<p id="currentCity"></p>
</div>
</body>
</head>
在script.ts文件中,我有:
4)在document.ready回調函數內部調用了我的getLocation()方法
5)嘗試將id =“ filler”的元素的html設置為某些內容
$(document).ready(function () {
getLocation();
/**
* called when the user clicks the "find weather" button
* get the user's current location, shows an error if the browser does not support Geolocation
*/
function getLocation(): void {
document.getElementById("filler").innerHTML = "is this showing up?";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
} else {
showError("Your browser does not support Geolocation!");
}
}
不幸的是,當我在瀏覽器中加載HTML文件時,id =“ filler”的文本不會更改為“是否顯示?”
我也嘗試過在repl.it上做類似的事情,並且可以按預期工作。
https://repl.it/@jonathanwangg/test
我在做什么錯/想念?
您的瀏覽器不了解打字稿。 它抱怨: void
部分。 您必須將文件編譯為常規javascript或只編寫javascript。 刪除: void
,它應該可以工作
另外,您不應該將openweathcermap api作為腳本src加載。 您正在加載jQuery,這意味着您可以使用jQuery ajax函數進行API調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.