[英]Use value of javascript variable within html page
So I am trying to make an html header which automatically changes the number on the header countdown style. 因此,我尝试制作一个HTML标头,该标头会自动更改标头倒计时样式上的数字。 I have a working javascript variable which returns the days until my event. 我有一个有效的javascript变量,该变量返回直到我的活动开始为止的日期。 How can I pull the number calculated by the variable "daysUntil" into a span id called countdown in html page? 如何将变量“ daysUntil”计算出的数字拉入html页面中名为spandown的范围ID?
I searched for a solution and found a few answers regarding getElementById but was unsure how to implement it. 我搜索了一个解决方案,并找到了一些有关getElementById的答案,但不确定如何实现。 I am JUST barely learning so thanks in advance if its a really basic question! 我只是勉强学习,因此,如果这是一个非常基本的问题,请先感谢!
<!DOCTYPE html>
<head>
<title>Countdown</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
var d1 = new Date(); //"now"
var d2 = new Date("2016/11/28") // some date
var diff = Math.abs(d2-d1)/(1000*60*60*24);
var daysUntil = Math.ceil(diff)
</script>
</head>
<body>
<div class="nav" id="top">
<ul>
<li><a href="/">COUNTDOWN</a></li>
<li><a href="portfolio.html">Portfolio</a></li>
<li><a href="connect.html">Connect with Me</a></li>
</ul>
</div>
<div class="clearfix" id="content">
<div class="left">
<h1>T Minus <span id="countdown"></span>days!</h1>
<!-- The rest of the code is omitted-->
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
This is the way to go, as well, as innerText
and innerHTML
. 这也是innerText
和innerHTML
的必经之路。
The simple example would go as follow 简单的例子如下
document.getElementById('countdown').textContent = daysUntil.toString()
You have to put your <script>
after your countdown element. 您必须将<script>
放在倒数元素之后。
...
<div class="left">
<h1>T Minus <span id="countdown"></span>days!</h1>
<script>
var d1 = new Date(); //"now"
var d2 = new Date("2016/11/28") // some date
var diff = Math.abs(d2-d1)/(1000*60*60*24);
var daysUntil = Math.ceil(diff);
var countdown = document.getElementById('countdown');
countdown.textContent = daysUntil + ' ';
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.