javascript - 当我点击按钮时,我的输入标签变空

标签 javascript html

我制作了一个表单,当我单击按钮时添加一些输入。这个按钮的功能是用javascript实现的。

但是当我点击它时,我所有的输入都变成空,我不希望这样。我想将信息保留在已有的输入中。

出了什么问题以及如何修复它?

var div = document.getElementById('participant');

function AjoutParticipant() {
  var ex = document.getElementsByClassName("bouton_plus");
  for (i = 0; i < ex.length; i++) {
    ex[i].style.display = "none";
  }
  div.innerHTML += '<label>Nom :</label><input type="text" name="nom[]" />' +
    '<label id="pre-decal">Prenom :</label><input type="text" name="prenom[]" />' +
    '<label id="ent-decal">Entreprise :</label><input type="text" name="entreprise" /><br/>' +
    '<button class="bouton_plus" type="button" onclick="AjoutParticipant()"><i class="fa fa-fw fa-plus"></i> Ajouter Participant</button>'
}
<fieldset id="participant">
  <legend>Participant(s)</legend>
  <label>Nom :</label><input type="text" name="nom[]" />
  <label>Prenom :</label><input type="text" name="prenom[]" />
  <label>Entreprise :</label><input type="text" name="entreprise" /><br/>
  <button class="bouton_plus" type="button" onclick="AjoutParticipant()"><i class="fa fa-fw fa-plus"></i> Ajouter Participant</button>
</fieldset>

最佳答案

您正在获取 div 的 innerHTML,向其附加一些新的 HTML,然后将其分配回来。

HTML 中的属性代表默认值,因此当用户在其中键入内容时它不会更新。

因此,当您覆盖 innerHTML 时,您会将输入重置为默认值。

<小时/>

不要使用innerHTML

相反,请使用 createElementappendChild 等 DOM 方法向 div 添加新内容,而无需重写现有内容。

关于javascript - 当我点击按钮时,我的输入标签变空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581994/

相关文章:

javascript - Webpack 文件加载器输出 [object Module]

javascript - Node.js for 循环 : strange behavior

jquery - 如何使用轮播隐藏和显示背景图像?

javascript - 每天更换视频

jquery - 移动下拉菜单汉堡包

javascript - 如何使用javascript为html中的按钮添加消息框

javascript - Angular 变量不更新外部循环

javascript - AngularJS:如何访问元素上的 clientWidth (普通 JS 方法)

javascript - 使用对象元素加载站点,然后自动填充其中的元素

javascript - Image Sprites 和 jQuery Mobile Ajax 导航的问题