所以我有这个代码,
spellNumber = 0
function createSpell() {
document.getElementById("spells").innerHTML +=
'<p><input type="text"></p><br />'
spellNumber += 1;
spellsActive = true
}
<a onClick="createSpell()" class="spellButton" style="background-color:#717171">Add a Spell</a>
<div id="spells"></div>
但是每当我尝试通过单击按钮添加另一个输入时,它都会删除以前的所有输入。我怎样才能阻止这种情况发生?
最佳答案
与现有 .innerHTML
连接意味着仅保留先前元素的 HTML 字符串 - 您的输入
没有.value
属性,因此值似乎丢失了。 (实际发生的情况是元素被破坏,然后使用新的完整 HTML 字符串重新创建。)
不要与现有的 innerHTML
连接,而是使用 createElement
,以免破坏容器中已存在的内容:
let spellNumber = 0;
const spells = document.getElementById("spells")
function createSpell() {
const p = spells.appendChild(document.createElement('p'));
const input = p.appendChild(document.createElement('input'));
spells.appendChild(document.createElement('br'));
spellNumber += 1;
spellsActive = true
}
<a onClick="createSpell()" class="spellButton" style="background-color:#717171">Add a Spell</a>
<div id="spells"></div>
另一种选择是使用 insertAdjacentHTML
,它与 appendChild
一样,不会损坏现有元素:
let spellNumber = 0;
const spells = document.getElementById("spells")
function createSpell() {
spells.insertAdjacentHTML('beforeend', '<p><input type="text"></input></p></br>');
spellNumber += 1;
spellsActive = true
}
<a onClick="createSpell()" class="spellButton" style="background-color:#717171">Add a Spell</a>
<div id="spells"></div>
关于javascript - 使用 JS 追加新输入会删除之前的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713519/