javascript - 如何将javascript代码中的变量打印到html正文中?
问题描述
我正在尝试创建一个网页,该网页将为我提供日出和日落时间,并使用我在GitHub 上找到的脚本。下面是我的代码...
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="sun.js"></script>
</head>
<body>
<input type="hidden" id="sunrise" value="" />
<input type="hidden" id="sunset" value="" />
<script>
navigator.geolocator.getCurrentPosition(function(position)){
sunrise = new Date().sunrise(position.coords.latitude, position.coords.longitude)
sunset = new Date().sunset(position.coords.latitude, position.coords.longitude)
}
document.getElementById('sunrise').value = sunrise;
document.getElementById('sunset').value = sunset;
</script>
//Want to put code here to print out the value of sunrise/sunset
</body>
</html>
我将如何在 HTML 正文中打印变量值?
解决方案
而不是.value
,使用.innerHTML
.
<!doctype HTML>
<html lang="en">
<head>
<script src="sun.js"></script>
</head>
<body>
<div id="sunrise"></div>
<div id="sunset"></div>
<script>
navigator.geolocation.getCurrentPosition(function(position) {
sunrise = new Date().sunrise(position.coords.latitude, position.coords.longitude);
sunset = new Date().sunset(position.coords.latitude, position.coords.longitude);
})
document.getElementById('sunrise').innerHTML = sunrise;
document.getElementById('sunset').innerHTML = sunset;
</script>
</body>
</html>
我还修复了一些语法错误,并且必须将<input>
s替换为<div>
s 以便显示输出。
推荐阅读
- ionic-framework - Ionic 3 中的键盘上推内容
- mysql - 使用 Inner Join 在 SQL 中查找我们关闭/赢得的机会的百分比是入站还是出站
- command-line - 是否可以使用 linux 命令行组合多个数组?
- python - Django Admin:JSONField 默认空字典不会保存在管理员中
- c# - 比较日期时间 SQL 服务器和 asp.net
- angular - 你如何在 Ngrx 中从一个 Effect 调度多个 Action
- java - Java - 带有轮廓的 Android Mobile Vision 人脸检测
- apache - Apache 启动后无法远程访问我的 EC2
- java - 如何从另一个范围调用变量?
- performance - MarkLogic 内容泵 (MLCP) - 性能 - 记录详细信息