【问题标题】:trying to get a timestamp inputed upon a click of the button尝试在单击按钮时输入时间戳
【发布时间】:2014-05-24 22:08:12
【问题描述】:

这是我正在处理的编码,无法弄清楚如何让按钮只输入当前时间的基本非计数时间戳。谁能帮我解决我的问题。我要做的就是在获取时间按钮旁边的框中放置一个时间戳...

<html>
<head>
<script language="JavaScript" type="text/javascript">



function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}


window.onclick = "getTimeStamp" ;


</script>

</head>

<body>
<td>
<button type="button" onclick="form"><form name="getTimeStamp">

 <input type=text" name="field" value="" size="11">
</form>Get Time</button></td>




<td>Test</td>
</tr>
</body>
</html>

【问题讨论】:

    标签: javascript html button input timestamp


    【解决方案1】:

    您不能将表单放在按钮中,按钮必须在表单中。你需要把返回值写在你能看到的地方。

    <form>
      <button type="button" onclick="this.form.timeField.value=getTimeStamp()">Get time stamp</button>
      <input type="text" name="timeField" size="11">
    </form>
    

    不要为文档中的任何元素指定与全局变量相同的名称或 ID(例如,名为“getTimeStamp”的表单和函数)。

    删除:

    window.onclick = "getTimeStamp";
    

    它将字符串“getTimeStamp”分配给windowonclick属性,但没有任何用处。

    您也可以删除:

    language="JavaScript" type="text/javascript"
    

    第一个只是很久以前在非常特殊的情况下才需要的,第二个除了在 HTML 4 中被要求之外从来没有真正需要。它不再需要了。 :-)

    【讨论】:

      【解决方案2】:

      在您的代码中存在一些基本错误。

      这是工作示例:

      <html>
      <head>
      <script type="text/javascript">
      function getTimeStamp() {
             var now = new Date();
             return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                           + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                           .getSeconds()) : (now.getSeconds())));
      }
      function setTime() {
          document.getElementById('field').value = getTimeStamp();
      }
      </script>
      
      </head>
      
      <body onload="setTime()">
      
      <input id="field" type="text" name="field" value="" size="11" />
      <button type="button" onclick="setTime();">Get Time</button>
      
      </body>
      </html>
      
      1. 你不能在button下嵌套form;在这种情况下,您可以跳过form
      2. 您需要以某种方式确定要设置时间的input
      3. 您可以通过设置 ID 来访问此input
      4. 在我的示例中,我使用 body 元素中的 onload 事件来设置初始时间戳

      如果你有任何问题,你可以问他们。

      【讨论】:

        猜你喜欢
        • 2022-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多