【问题标题】:How to insert text displayed by span inside input form如何在输入表单中插入跨度显示的文本
【发布时间】:2021-09-30 01:25:32
【问题描述】:
document.querySelector('.input').value = document.querySelector('.text').innerHTML
document.querySelector('.text').textContent = 'Here is the text';
<span class='text'></span>
<input class='input' />
如何在输入表单中插入“这是文本”。
【问题讨论】:
标签:
javascript
html
forms
input
【解决方案1】:
你只是把 2 行颠倒了。
此外,您可能希望将其包装在 window.load 侦听器中,以确保它在页面呈现后触发
window.addEventListener('DOMContentLoaded', () => {
document.querySelector('.text').textContent = 'Here is the text';
document.querySelector('.input').value = document.querySelector('.text').innerText
})
<span class='text'></span>
<input class='input' />
【解决方案2】:
您需要在设置span的textContent后设置该值,否则innerHTML属性将是"",因为当时span没有任何内容:
document.querySelector('.text').textContent = 'Here is the text';
document.querySelector('.input').value = document.querySelector('.text').innerHTML
<span class='text'></span>
<input class='input' />