如何在页面加载时直接使用Javascript在输入字段中填写数据

How to fill in data in an input field using Javascript directly on page load?

本文关键字:字段 输入 Javascript 数据 加载      更新时间:2023-09-26

这个问题被问了很多——似乎是在Stack Overflow上,但似乎没有一个解决方案有效。我正在开发一个web应用程序,我必须在页面加载的数据字段中填写数据。这是我的代码:

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<input type="text" id="datetime" value="" />
<script type="text/javascript">
$(document).on("pageload",function(){
//for fill field
document.getElementById("datetime").value = "here is value";
});
</script>

</body>
</html>

出于某种原因,当我加载页面时,没有数据被填充,有人看到原因吗?

您不需要jQuery。试试这个:

<!DOCTYPE html>
<html>
<body>
  <input type="text" id="datetime" value="" />
  <script>
    window.onload = function() {
      document.getElementById('datetime').value = 'here is value';
    };
  </script>
</body>
</html>

您使用的是什么版本的jquery?看起来页面加载可能会被弃用,您应该使用pagecontainerload

还是最好使用$(document).ready或.load方法?

在Jquery中,它被称为document ready事件。。。因此,请使用以下语法。

$(document).ready(function(){
 //for fill field
 $("#datetime").val( "here is value");
});

请注意,代码的内部行已更改。。这是Jquery做同样事情的方式。。。您也可以将此Shorthand用于$(document).ready(function(){这就是$(function(){