简体   繁体   中英

How to pass value of date variable from javascript to html

I want to print the value of the date by passing it from the JavaScript file to the HTML file.

HTML file:

  <html> 
      <body> 
          <script src=background.js> </script> 
          <span id="showDate"> </span> 
      </body> 
  </html>

JavaScript file:

document.body.style.background = "url('1.jpg')";
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
  dd='0'+dd
} 
if(mm<10) {
  mm='0'+mm
} 
today = dd+'/'+mm+'/'+yyyy;
alert(today);
document.getElementById("showDate").value=today;

最简单的方法:

 document.getElementById("showDate").textContent = today;

You just need to use textContent instead of value .

Live Working Demo:

 document.body.style.background = "url('1.jpg')"; var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } today = dd + '/' + mm + '/' + yyyy; document.getElementById("showDate").textContent = today; 
 <span id="showDate"> </span> 

JSFiddle Version: https://jsfiddle.net/ae6wfz12/

First of all link up your javascript file like into HTML file bottom part.

<script src="your_javascript_file.js"></script>

and then

Write Your js code into your js file with flowing line and pass inner html into

document.getElementById("showDate").innerHTML = today;

First of all, you need to put the scripts that access document elements at the end of the body tag, so that they are executed only after the required elements are loaded.

 <html> 
      <body> 
          <span id="showDate"> </span> 
      </body> 
      <script src=background.js> </script>
  </html>

Secondly, as Maximillian told, use textConten or innerHTML or innerText property of the selected element to get or set the value.

document.getElementById("showDate").innerHTML = '<strong>' + today '</strong>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM