首页 > 解决方案 > 如何将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 正文中打印变量值?

标签: javascripthtml

解决方案


而不是.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 以便显示输出。


推荐阅读