首页 > 解决方案 > 如何在不使用javascript清除值的情况下将输入字段附加到div

问题描述

我有这段代码,通过单击按钮将包含输入字段和文本区域的 div 附加到父 div。当我附加 div 并在字段中输入一些值然后附加一个新的 div 时,输入字段的值会以某种方式变为空。它如何解决这个问题?

这是代码:

let counter = 1;
let new_section = document.getElementsByClassName("addnew")[0];
document.getElementById("shownew").addEventListener("click", (e) => {
  e.preventDefault();

  new_section.innerHTML += `   <div class="lowerlayer2">
  <input type="text" placeholder="Word Type" id="wtype${counter}" />
  <input type="text" placeholder="Synonym" id="syn${counter}" />
  <input type="text" placeholder="Antonyms" id="anty${counter}" />

  <textarea
    cols="30"
    rows="10"
    placeholder="History & Etymology"
    id="history${counter}"
  ></textarea>
  <textarea
    cols="30"
    rows="10"
    placeholder="Examples"
    id="example${counter}"
  ></textarea>
  <textarea
    cols="30"
    rows="10"
    placeholder="Definition 1"
    id="def1${counter}"
  ></textarea>
  </div>`;

  counter++;
});

标签: javascripthtml

解决方案


innerHTML += 覆盖整个 HTML 而不是简单地添加它。值不包括在覆盖中。

如果您不介意插入附加节点,appendChild() 将按预期添加到 div。在您的情况下,无论如何您都在添加一个 div ,所以没关系。

var newInfo = document.createElement('div'); // this makes a node, a node is require for appendChild. You could also use 'p' or 'span' etc.
newInfo.setAttribute("class", "lowerlayer2"); // you can add your classes and id etc with setAttribute
newInfo.innerHTML = "data to be added/appended";
document.getElementById("newtestdiv").appendChild(newInfo);
        

推荐阅读