【问题标题】:Appending new inputs with JS wipes previous ones使用 JS 附加新输入会擦除以前的输入
【发布时间】:2018-12-11 05:00:16
【问题描述】:

所以我有这个代码,

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 内容的坏方法。

标签: javascript html html-input


【解决方案1】:

与现有的.innerHTML 连接意味着只保留先前元素的HTML 字符串 - 您的inputs 没有.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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    相关资源
    最近更新 更多