如何在 JavaScript 中每次点击按钮时添加一个新的文本框?

问题描述 投票:0回答:1

这是我目前拥有的代码...

<button id="a" onclick="c()"></button>

<div id="b"></div>
function c()
{
    var Html = '<input type="text" id="a">';
    document.getElementById('b').innerHTML = Html;
}

问题是,当点击按钮多次时,它只添加一个文本框。我需要它在每次点击时添加一个文本框。

javascript html web textbox
1个回答
0
投票

使用

insertAdjacentHTML()
将 HTML 附加到元素(永远不要这样做
.innerHTML += html
,因为它会破坏之前添加的元素(由于在 Stackoverflow 上报告为问题而导致的错误日志)。

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

function c()
{
    var Html = '<input type="text" id="a">';
    document.getElementById('b').insertAdjacentHTML('beforeend', Html);
}
<button id="a" onclick="c()">Append</button>

<div id="b"></div>

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.