开发者问题收集

未捕获的类型错误:在浏览器上运行时无法将属性“value”设置为 null

2018-11-02
1211

我想在输入文本上显示今天的日期。但是为什么我在浏览器上运行后会收到错误?代码有什么问题吗?

HTML

 <!DOCTYPE html >
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <title>Insert title here</title>
 <script  type=text/javascript>


 var today = new Date();
 var dd = today.getDate();
 var mm = today.getMonth()+1; //January is 0!
 var yyyy = today.getFullYear();


 if(dd<10) {
dd = '0'+dd
} 

if(mm<10) {
mm = '0'+mm}

 today= mm + '/' + dd + '/' + yyyy;
 document.getElementById("today1").value=today;
 </script>
<body>

<input id="today1" value="">
</body>
</html>
3个回答

仅在 DOM 加载后运行 javaScript。

document.addEventListener("DOMContentLoaded", function(event) {
 var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();


if(dd<10) {
    dd = '0'+dd
} 

if(mm<10) {
    mm = '0'+mm}

 today= mm + '/' + dd + '/' + yyyy;
 document.getElementById("today1").value=today;
});
Sagar Bahadur Tamang
2018-11-02

您的代码在 DOM 准备就绪之前运行。使用 DOMContentLoaded 包装您的代码。这将确保在所有初始 HTML 完全加载和解析后执行代码。

document.addEventListener("DOMContentLoaded", function(event) {
  // your code here
});

工作代码示例:

<script  type=text/javascript>
  document.addEventListener("DOMContentLoaded", function(event) {

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();


    if(dd<10) {
    dd = '0'+dd
    } 

    if(mm<10) {
    mm = '0'+mm}

    today= mm + '/' + dd + '/' + yyyy;
    document.getElementById("today1").value=today;
  });
</script>


<input id="today1" value="">
Mamun
2018-11-02

此链接处的代码可能对您有帮助 这里

Nimit Vachhani
2018-11-02