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

Chrome控制台JS脚本问题:输入框内容无法同步更新至h1标签

问题原因与解决方法

你的代码仅完成了元素创建和页面挂载的工作,但没有给输入框绑定输入事件监听——当用户在输入框中输入内容时,没有对应的逻辑去更新h1标签的文本,所以h1内容不会随输入变化。

要实现实时更新效果,需要给输入框添加input事件监听,在事件触发时将输入框的值同步到h1的innerText中。修改后的代码如下:

var h1 = document.createElement('h1')
h1.innerText = "Type into the input to make this text change"

var input = document.createElement('input')
input.setAttribute('type', 'text')

// 添加输入事件监听,实时同步输入内容到h1
input.addEventListener('input', function() {
  h1.innerText = this.value || "Type into the input to make this text change";
})

document.body.innerText = '';
document.body.appendChild(h1);
document.body.appendChild(input);

补充说明:

  • input事件会在输入框内容发生任何变化时触发(包括键盘输入、鼠标粘贴等操作)
  • 回调中通过this.value获取输入框当前内容,为空时恢复初始提示文本,避免h1显示空白

内容的提问来源于stack exchange,提问作者Patricia Cosma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:54:24