简体   繁体   中英

Add current date using inline javascript

The date is not showing up in the output when I run the following code. I can't seem to figure out why the date won't show up...

 <!DOCTYPE html> <html> <head> <title>document.write() Example</title> </head> <body> <p>The current date and time is: <script type=”text/javascript”> document.write(“<strong>” + (new Date()).toString() + “</strong>”); </script> </p> </body> </html> 

Because you are using these types of quotes: “ ... ” . You need to use " ... "

<script type="text/javascript">
    document.write("<strong>" + (new Date()).toString() + "</strong>");
</script>

Snippet:

  document.write("<strong>" + (new Date()).toString() + "</strong>"); 

Do it as the way the samurais do it...

<!DOCTYPE html>
<html>
  <head>
    <title>Example</title>
  </head>
  <body>

    <p>The current date and time is: <span id="myDate"></span> </p>

    <script>

      var d = new Date;
      var date = d.toString();

      span = document.getElementById('myDate');
      txt = document.createTextNode(date);
      span.innerText = txt.textContent;

    </script>


  </body>
</html>

You can try this snippet. It is similar to what you used but avoid using document.write.
Plus is safer because it cannot overwrite all the document if it was loaded.

 <p id="date"></p> <script> date = document.getElementById("date"); date.innerHTML = new Date(); </script> 

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