代码之家  ›  专栏  ›  技术社区  ›  Ryan Salmons

在HTML加载Javascript中输入日期

  •  0
  • Ryan Salmons  · 技术社区  · 10 年前

    我试图在加载页面时输入当前日期。我能够将其存储到一个变量中,我只是在将该变量输入页面时遇到了问题。

    HTML格式:

    <span id='test'>x</span>
    

    Java脚本:

    window.onload = function() {
      var month = new Array("January", "February", "March", "April", "May", "June", "July",    "August", "September", "October", "November", "December");
      var today = new Date();
      var dd = today.getDate();
      var mm = today.getMonth();
      var currentMonth = month[mm];
      var yyyy = today.getFullYear();
      today = currentMonth + ' ' + dd + ', ' + yyyy;
      document.getElementById('test').innertext() = today;
    }
    

    JSFIDDLE

    3 回复  |  直到 10 年前
        1
  •  3
  •   Leonardo Delfino    10 年前

    更改此项:

    document.getElementById('test').innertext() = today;
    

    为此:

    document.getElementById('test').innerHTML = today;
    
        2
  •  0
  •   Jagadesh K    10 年前

    使用此代码,它有效

    window.onload = function() {
          var month = new Array("January", "February", "March", "April", "May", "June", "July",    "August", "September", "October", "November", "December");
          var today = new Date();
          var dd = today.getDate();
          var mm = today.getMonth();
          var currentMonth = month[mm];
          var yyyy = today.getFullYear();
          today = currentMonth + ' ' + dd + ', ' + yyyy;
          document.getElementById('test').innerHTML = today;
        }
    
        3
  •  0
  •   Yair Nevet    10 年前

    您在以下代码行遇到问题,因为您处理 innerText 就像它是一个 function 并且不区分大小写(JavaScript是一种区分大小写的语言):

     document.getElementById('test').innertext() = today;
    

    因此,将其更改为:

    document.getElementById('test').innerText = today;
    

    下面是一个工作示例: http://jsfiddle.net/ynevet/cNCf4/