这里的初学者:(
我正在尝试编写一个脚本,该脚本将从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不会随着输入的文本而改变。
你能分享一下你的想法吗?为什么你认为这不起作用?
谢谢。
您需要为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);