【问题标题】:Input doesn't change using this code in the console在控制台中使用此代码不会更改输入
【发布时间】:2022-08-21 21:35:53
【问题描述】:

这里的初学者:)

我正在尝试编写一个脚本,该脚本将从 HTML 表单中获取输入,并使用 Chrome 控制台中的 JS 在屏幕上显示用户输入的文本。 我有以下代码:

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\')

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

输入工作,我可以在那里输入任何类型的文本。 但是,h1 不会随着输入中的文本而改变。

您能否分享您对为什么认为这不起作用的想法?

谢谢你。

  • 任何地方都没有代码 a) 对输入的输入做出反应 b) 尝试更改 h1 的文本?

标签: javascript html console dom-manipulation


【解决方案1】:

您需要为input 元素添加input 事件侦听器,并根据input 值更改h1 值。

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

var input = document.createElement('input')
input.addEventListener('input', (e) => {
   h1.textContent = e.target.value
})
input.setAttribute('type', 'text')

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    相关资源
    最近更新 更多