You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

复制W3Schools示例报错:Uncaught TypeError问题求助

解决"Cannot read properties of null (reading 'value')"错误并实现输入框定时更新内容

错误原因

你的JS代码在HTML输入框元素加载完成之前就执行了,document.getElementById("txt")找不到对应的DOM元素,返回null,后续尝试访问null.value就会抛出这个类型错误。

修复方案

以下是几种可行的解决方式:

1. 将JS代码放在HTML元素之后

把脚本放在<input>标签的下方,确保DOM元素已经被浏览器解析完成后再执行JS代码:

<input type="text" id="txt">
<script>
let x = document.getElementById("txt");
setTimeout(function(){ x.value="2 seconds"}, 2000);
setTimeout(function(){ x.value="4 seconds" }, 4000);
setTimeout(function(){ x.value="6 seconds" }, 6000);
</script>

2. 使用DOMContentLoaded事件监听

把JS代码包裹在DOMContentLoaded事件回调里,确保页面所有DOM元素加载完成后再执行:

<input type="text" id="txt">
<script>
document.addEventListener('DOMContentLoaded', function() {
  let x = document.getElementById("txt");
  setTimeout(function(){ x.value="2 seconds"}, 2000);
  setTimeout(function(){ x.value="4 seconds" }, 4000);
  setTimeout(function(){ x.value="6 seconds" }, 6000);
});
</script>

3. 给script标签添加defer属性

如果你的JS代码放在<head>标签内,可以给<script>标签加上defer属性,让脚本在DOM解析完成后再执行:

<head>
  <script defer>
    let x = document.getElementById("txt");
    setTimeout(function(){ x.value="2 seconds"}, 2000);
    setTimeout(function(){ x.value="4 seconds" }, 4000);
    setTimeout(function(){ x.value="6 seconds" }, 6000);
  </script>
</head>
<body>
  <input type="text" id="txt">
</body>

优化建议(可选)

可以用setInterval简化代码逻辑,避免重复调用setTimeout:

<input type="text" id="txt">
<script>
document.addEventListener('DOMContentLoaded', function() {
  const input = document.getElementById("txt");
  let seconds = 2;
  const interval = setInterval(() => {
    input.value = `${seconds} seconds`;
    seconds += 2;
    if (seconds > 6) {
      clearInterval(interval);
    }
  }, 2000);
});
</script>

内容的提问来源于stack exchange,提问作者Şamil Ertuğrul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:10:57