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

点击按钮后添加至div的文本无法保留的前端问题求助

问题原因

你遇到的问题是表单默认提交行为导致页面刷新:

  • 表单内的按钮默认类型为submit,点击后会触发表单提交,页面会重新加载
  • 弹出alert时页面还未完成刷新,所以能看到添加的内容;关闭alert后表单提交完成,页面刷新,所有动态添加的元素都会被重置
解决方法

要阻止表单的默认提交行为,有两种简单的实现方式:

方式1:修改按钮类型(推荐)

直接给表单内的按钮加上type="button",让按钮不再触发表单提交:

<!-- 修改关闭按钮 -->
<button class="x" type="button">&times;</button>

<!-- 修改Submit按钮 -->
<button class="submit" type="button" onclick="createDiv();">Submit</button>

方式2:在JS中阻止默认事件

给createDiv函数添加事件参数,调用preventDefault()阻止表单提交:

function createDiv(event) {
  // 阻止表单默认提交行为
  event.preventDefault();
  alert("working");
  let cards = document.querySelector(".cards");
  let strong = document.createElement("strong");

  strong.textContent = "strong";
  cards.append(strong);
}

同时修改HTML中的Submit按钮,传递事件参数:

<button class="submit" onclick="createDiv(event);">Submit</button>
补充:完善模态框关闭功能

当前关闭按钮(×)没有实际关闭模态框的功能,添加以下JS代码实现关闭:

x.addEventListener('click', function() {
  cardsContainer.style.display = "none";
});
修改后的完整代码

HTML代码

<!DOCTYPE html>
<html>

<head>
  <title>Library Project</title>
  <link rel="stylesheet" href="styles.css">
  <script src="practice.js" defer></script>
</head>

<body>

  <div class="container">

    <div class="header">
      <h1>Library</h1>
    </div>

    <div class="bottomContainer">

      <div class="button">
        <button id="newBook" onclick="displayCard();">New Book</button>
      </div>

      <div class="cardsContainer">
        <div class="window">
          <form action="">
            <div class="close-btn">
              <p>Add A New Book</p>
              <button class="x" type="button">&times;</button>
            </div>
            <input type="text" placeholder="Title" id="title" value="">
            <input type="text" placeholder="Author" id="author" value="">
            <input type="text" placeholder="Pages" id="pages" value="">
            <button class="submit" type="button" onclick="createDiv();">Submit</button>
          </form>
        </div>
      </div>

      <div class="cards"></div>

    </div>

  </div>
</body>
</html>

JavaScript代码

// Button Stuff //
let newBook = document.getElementById("newBook");
let cardsContainer = document.querySelector(".cardsContainer");
let x = document.querySelector(".x");

// Brings up & closes form window //
function displayCard() {
  cardsContainer.style.display = "flex";
}

//  Creates Div  //
function createDiv() {
  alert("working");
  let cards = document.querySelector(".cards");
  let strong = document.createElement("strong");

  strong.textContent = "strong";
  cards.append(strong);
}

// 关闭模态框
x.addEventListener('click', function() {
  cardsContainer.style.display = "none";
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:05:33