我试图在文档加载完成后使用JavaScript在HTML中设置段落元素的值,但它似乎不起作用。
从带有红色下划线的图片中,我指出:
1)我已经从谷歌的CDN中包含了jQuery库。
2)我已经与我的HTML文件“链接”(不确定正确的词是什么)我的.ts文件。
3)我已经将段元素的id设置为“填充”
<!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调用。