试图在点击按钮时输入时间戳

trying to get a timestamp inputed upon a click of the button

本文关键字:输入 时间戳 按钮      更新时间:2023-09-26

这是我正在工作的编码,无法弄清楚如何有一个按钮,只是从当前时间输入一个基本的非计数时间戳。有人能帮我解决这个问题吗?所有我想做的是有一个时间戳被放置在一个框旁边的获取时间按钮…

<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>

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

<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"分配给窗口onclick属性,而不做任何有用的事情。

也可以删除:

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

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

在你的代码中有一些基本的错误。

这是一个工作示例:

<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
  4. 来访问此input
  5. 在我的例子中,我使用onload事件在body元素设置初始时间戳
如果你有什么问题可以问他们。