我正在尝试创建一个按钮,单击该按钮时会创建一个回车符。例如,在我的网页顶部有一些按钮,单击后会输出单词。单击下一个按钮后,新单词将立即放置在其他单词之后。我需要这个按钮来为其上方的输出单词创建一个新行。我已经尝试了一些代码:
<input type="button" value="Return"
onclick="document.getElementById('outputDiv').innerHTML=
document.getElementById('outputDiv').innerHTML + \br;">
<div id="outputDiv"></div>
任何帮助将不胜感激。
最佳答案
尽量避免使用 .innerHTML
,而是考虑 node.appendChild
和 document.createElement
的 DOM 方法>
function newline() {
document.getElementById('outputDiv').appendChild(
document.createElement('br')
);
}
// after input exists, select it with your favourite method to attach listener
document.querySelector('input[value="Return"]').addEventListener(
'click',
newline
);
以这种方式附加时,HTML 也不再需要 onclick 属性
<input type="button" value="Return" />
<div id="outputDiv"></div>
关于javascript - 在 JavaScript 中创建回车按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29722970/