使用innerHTML连接HTML时防止重新加载HTML元素 [英] Prevent HTML element reload when concatenating HTML using innerHTML

查看:54
本文介绍了使用innerHTML连接HTML时防止重新加载HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个输入字段的表单:

I have a form having two input fields:

<form id="import-products-form">
  <div class="form-row">
    <select></select>
    <input>
  </div>
</form>

还有一个按钮:

<button id="add-input-button"><strong>+</strong></button>

每次单击该按钮时,都会在表单中添加两个输入字段:

Everytime the button is clicked, two input fields will be added to the form:

document.getElementById("add-input-button").onclick = () => {
  const input = `
    <div class="form-row">
      <select></select>
      <input>
    </div>
  `;

  document.getElementById("import-products-form").innerHTML += input;
};

这里的问题是,每当单击按钮时,现有字段的值都将重置为默认值.在 DevTools 中,我看到单击按钮时就重新加载了整个表单.将新字段添加到表单时,是否仍要保留现有字段的值?

The problem here is whenever the button is clicked, the values of the existed fields will be reset to default. In DevTools, I saw that the entire form was reloaded when the button clicked. Is there anyway to keep the values of the existed fields when new fields added to the form?

推荐答案

请勿分配给 innerHTML .这将导致从头开始重新创建表单中的所有元素,并且所有动态状态都将丢失.

Don't assign to innerHTML. That causes all the elements inside the form to be recreated from scratch, and any dynamic state is lost.

使用 insertAdjacentHTML 代替.这将解析新的HTML并追加DOM元素,而不会干扰原始元素.

Use insertAdjacentHTML instead. This parses the new HTML and appends the DOM elements, without disturbing the original elements.

document.getElementById("import-products-form").insertAdjacentHTML('beforeend', input);

这篇关于使用innerHTML连接HTML时防止重新加载HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆