我正在尝试添加一个字段供用户输入文本,并将该文本添加到当前 div 中显示的新段落元素中。
但是,我收到的是 [object] 而不是用户输入。这是因为它还不是字符串值吗?我一直在尝试将对象转换为字符串,但不断返回错误。
function addText(){
var newParagraph = document.createElement('p');
var input = document.getElementById('userInput');
newParagraph.className = 'red';
newParagraph.appendChild(document.createTextNode(input));
document.getElementById('content').appendChild(newParagraph);
}
function getText(){
addText();
}
我使用输入 ID“userInput”,并使用 onClick = "getText()"
触发按钮上的函数。除了返回 [object] 而不是 userInput 文本之外,脚本工作正常。
HTML:
<input type="text" id="userInput" />
<button id="button" onClick="getText()">Insert Text</button>
最佳答案
您需要获取输入的值,现在您将整个输入作为对象分配给您的var input
,所以它应该是:
var input = document.getElementById('userInput').value;
关于javascript - 将用户输入从文本框附加到新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11069290/