javascript - 如何在不使用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++;
});
解决方案
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);
推荐阅读
- javascript - 如何通过json_encode重定向php页面
- mysql - 需要帮助连接 SQL
- c# - 使用 c# 与 java/c++ 比较的 grpc 的性能基准数
- postgresql - 等待状态显示缓冲区引脚
- c - 当 xTicksToWait = portMAX_DELAY 时,xQueueReceive 会失败吗?
- python - python'jwt'模块没有属性'encode'
- java - 限制用户在 java swing 中打开的 jframe 不超过 1 个
- java - 为什么不触发 Firebase 中的 onDisconnect?
- ios - 我可以在 SFSafariViewController 中从 Safari 获取 cookie 吗?
- java - 如何验证json的每个对象和键值