Javascript 的新手。我想在用户单击按钮时将时间戳传递给表单,但我无法获取要提交的实际值。
<html>
<head>
<script type="text/javascript">
var dateOfUser = new Date();
document.getElementById("userdate").value = dateOfUser;
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
// hide the content from user until they click the button
<script>
$(document).ready(function(){
$("#show").click(function(){
$("#ans").show();
});
});
</script>
</head>
<body>
<p>
Click the button to see the text.
</p>
<p><button type="button" id="show" onclick="userdate = new Date()">Show text</button></p>
<div id="ans" style="display:none">
<input type="hidden" id="userdate" name="timestamp" value="dateOfUser">
Here is the hidden text.
</div>
</body>
我省略了表单提交代码 - 遗憾的是我没有编写它,而且除了将其用于表单提交之外,我无权访问该代码。
但是提交后,.csv 文件包含:
"timestamp":"dateOfUser"
而不是“userdate”的值。据我所知,使用 document.getElementById("userdate").value = dateOfUser;
应该允许我在 HTML 中使用“userdate”。
任何帮助将不胜感激,我已经在此站点和其他站点上提出了许多类似的问题,但我无法弄清楚我做错了什么。
最佳答案
您可以删除 type="hidden"
进行测试。至少它适用于我使用 userdate.value
。
<html>
<head>
</head>
<body>
<p>
Click the button to see the text.
</p>
<p><button type="button" id="show">Show text</button></p>
<div id="ans" style="display:none">
<input id="userdate" name="timestamp" value="dateOfUser">
Here is the hidden text.
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
// hide the content from user until they click the button
<script>
$(document).ready(function(){
$("#show").click(function(){
$("#ans").show();
$("#userdate")[0].value = new Date()
});
});
</script>
</body>
将 script
放在正文上方的方式
<script type="text/javascript">
var dateOfUser = new Date();
document.getElementById("userdate").value = dateOfUser;
</script>
不会工作,因为 dom(即元素)尚未加载。而onclick
和$(document).ready
则与上述方式不同。
不过,还是把script
放在body的底部比较好。
关于javascript - 单击按钮时将时间戳传递给表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57830560/