You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript通过表单创建div/section时元素生成后快速消失如何解决

问题解决方法

问题根源

你当前代码只在表单校验不通过时才阻止默认提交行为,校验通过时没有阻止浏览器默认的表单提交逻辑:

  • 你的form标签action属性为空,表单提交后会默认刷新当前页面
  • 你用JS动态渲染的元素仅存在于当前页面的DOM中,页面刷新后就会被清空,所以会出现元素短暂出现后消失的现象

修复方案

你这个场景是纯前端动态渲染元素,完全不需要表单提交到后端,直接在提交事件的最开头统一阻止默认行为即可,同时修复你代码中变量未声明的小问题:

/*get the number of element the text and the type*/
let element = document.querySelector("[name='elements']");
let text = document.querySelector("[name='texts']");
let type = document.querySelector("[name='type']");
let result = document.querySelector(".results");

document.forms[0].onsubmit = function (e) {
  // 新增:统一阻止表单默认提交刷新行为,这是解决问题的核心
  e.preventDefault();

  let validElement = false;
  let validText = false;
  let validType = false;
  document.querySelectorAll(".results .box").forEach((box) => box.remove());

  if (element.value !== "" && text.value !== "" && type.value !== "" && element.value > 0) {
    
    for (let i = 0; i < element.value; i++) {
      // 新增let声明变量,避免变成全局变量
      let myBox = document.createElement(type.value);
      
      myBox.className = "box";
      myBox.id = `id-${i+1}`;
      myBox.title = "Element";
      
      // 新增let声明变量
      let myText = document.createTextNode(text.value);
      
      myBox.appendChild(myText);
      result.appendChild(myBox);
    }
    
    validElement = true;
    validText = true;
    validType = true;
  }
};

可选优化建议

你可以把下拉框的option值改成全小写的div、section,更符合DOM规范:

<select name="type" class="input">
  <option value="div">Div</option>
  <option value="section">Section</option>
</select>

内容的提问来源于stack exchange,提问作者Mohamad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:36:04