提问者:小点点

防止在修改parend时清除输入


我能对此提供一些意见吗?

当表单或表单的父元素被修改时,在表单输入中键入的文本将被清除。 正如这篇文章所示:

null

function modifyParent() {
  document.getElementById("parent").innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
  <input type="text" id="child">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>

null

大家好,

如果我知道父项被修改的位置,我找到了一种防止它的第一种esay方法。 正如这个剪辑器所显示的

null

function modifyParent() {
  var child = document.getElementById("child");
  child.setAttribute("value", child.value)
  document.getElementById("parent").innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
  <input type="text" id="child" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>

null

这个解决方案看起来很棒,但前提是我知道修改父项时的位置。 另外,如果我有多个输入,我需要在document.getElementsByTagName(“input”)上循环。

由于我不知道我有多少按钮和多少输入,这是我目前为止最好的解决方案:

null

function modifyParent() {
  setInputValues();
  document.getElementById("parent").innerHTML += "<br>a line get added";
}

function setInputValues() {
  for (var c of document.getElementsByTagName("input"))
    c.setAttribute("value", c.value);
}
<div id="parent">
<form>
  <input type="text" value="">
  <input type="text" value="">
  <input type="text" value="">
  <input type="text" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>

null

对于多个输入,它工作得很好,但是每次修改父项之前,我必须调用setInputValues()函数。 我开始考虑在这个函数上添加setInterval,但我在这里停下来,因为我开始走得有点远,很可能他们是一个更好的方法。

任何帮助都将被接受


共1个答案

匿名用户

更干净的解决方案是为消息使用一个新元素。 通过这种方式,您可以在容器中设置消息,而不会干扰输入。

null

const messageBox = document.querySelector(".messages");
function modifyParent() {
  messageBox.innerHTML += "<br>a line get added";
}
<div id="parent">
  <form>
    <input type="text" value="">
    <input type="text" value="">
    <input type="text" value="">
    <input type="text" value="">
  </form>
  
  <button type="button" onclick="modifyParent()">click</button>
  
  <div class="messages"></div>
</div>