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

点击删除按钮将JSON数据is_active设为false并实现弹窗确认

实现带确认模态框的软删除功能(更新is_active为false)

看起来你想要实现软删除功能(把is_active设为false而非真正删除条目),同时需要确认弹窗,还要解决前端数据更新的问题。先给你指出现有代码的几个小问题,再一步步实现完整功能:


第一步:修复现有代码的核心问题

你循环里给所有删除按钮都加了id='btnDelete',但HTML里id必须唯一,这会导致后续JS无法正确绑定事件。我们把id改成class,同时给按钮添加data-id属性存储对应条目的ID:

修改表格行里的删除按钮代码:

<a href='#' class='btn btn-danger btn-sm btnDelete' role='button' data-toggle='modal' data-target='#exampleModal' data-id='${response[x].id}' style='margin-left: 10px;'>Delete</a>

(把href='index.php'改成href='#'避免页面跳转,我们用JS处理逻辑)


第二步:添加Bootstrap确认模态框

既然你用了Bootstrap的data-toggle和data-target,直接在页面body里添加模态框结构即可:

<!-- 确认删除模态框 -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">确认操作</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        你确定要标记这条记录为已删除吗?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-danger" id="confirmDelete">确认删除</button>
      </div>
    </div>
  </div>
</div>

第三步:编写完整JavaScript逻辑

我们需要完成:获取待删除ID、确认后更新数据、重新渲染表格这几个核心步骤。这里分两种数据存储场景(纯前端模拟/后端接口支持):

完整JS代码(含原有渲染逻辑+删除功能)

// 全局变量存储当前要删除的条目ID
let currentDeleteId = null;
// 存储所有人员数据,方便后续修改
let peopleData = [];

document.addEventListener('DOMContentLoaded', function() {
  // 1. 加载并渲染初始数据
  loadAndRenderData();

  // 2. 绑定删除按钮点击事件,获取待删除ID
  document.addEventListener('click', function(e) {
    if (e.target.classList.contains('btnDelete')) {
      e.preventDefault(); // 阻止默认跳转
      currentDeleteId = e.target.getAttribute('data-id');
    }
  });

  // 3. 绑定模态框确认按钮事件
  document.getElementById('confirmDelete').addEventListener('click', function() {
    if (!currentDeleteId) return;

    // 找到对应条目,更新is_active为false
    const targetItem = peopleData.find(item => item.id === currentDeleteId);
    if (targetItem) {
      targetItem.is_active = 'false'; // 匹配你JSON里的字符串类型

      // --- 数据更新分两种场景 ---
      // 场景A:纯前端模拟(用localStorage存储数据)
      localStorage.setItem('peopleData', JSON.stringify(peopleData));

      // 场景B:有后端支持(发送请求到后端修改JSON文件,示例用fetch)
      // fetch('update-data.php', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({ id: currentDeleteId, is_active: 'false' })
      // })
      // .then(res => res.json())
      // .then(() => console.log('数据更新成功'))
      // .catch(err => console.error('更新失败:', err));

      // 重新渲染表格
      loadAndRenderData();
      // 关闭模态框
      $('#exampleModal').modal('hide');
      // 清空当前ID
      currentDeleteId = null;
    }
  });
});

// 封装加载数据的函数
function loadAndRenderData() {
  const outputEl = document.getElementById('output');
  const url = "form.json";

  // 优先从localStorage读取(如果是纯前端场景)
  const storedData = localStorage.getItem('peopleData');
  if (storedData) {
    peopleData = JSON.parse(storedData);
    renderTable(peopleData);
    return;
  }

  // 初始从JSON文件加载
  const xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      peopleData = JSON.parse(xhttp.responseText);
      // 第一次加载后存入localStorage
      localStorage.setItem('peopleData', JSON.stringify(peopleData));
      renderTable(peopleData);
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}

// 封装表格渲染函数
function renderTable(data) {
  let output = '';
  output += "<table class='table table-bordered'>";
  output += "<tr><th scope='col'>id</th><th>First Name</th><th>Last Name</th><th>Age</th><th>Status</th><th>Action</th></tr>";
  
  // 渲染时标记活跃状态,也可以过滤掉已删除条目
  data.forEach(item => {
    const statusClass = item.is_active === 'true' ? 'text-success' : 'text-danger';
    const statusText = item.is_active === 'true' ? 'Active' : 'Inactive';
    
    output += `<tr>
      <td>${item.id}</td>
      <td>${item.firstname}</td>
      <td>${item.lastname}</td>
      <td>${item.age}</td>
      <td class="${statusClass}">${statusText}</td>
      <td>
        <a href='edit.php?id=${item.id}&firstname=${item.firstname}&lastname=${item.lastname}&age=${item.age}' class='btn btn-primary btn-sm active' role='button' aria-pressed='true'>Edit</a>
        <a href='#' class='btn btn-danger btn-sm btnDelete' role='button' data-toggle='modal' data-target='#exampleModal' data-id='${item.id}' style='margin-left: 10px;'>Delete</a>
      </td>
    </tr>`;
  });
  
  output += "</table> ";
  outputEl.innerHTML = output;
}

关键说明

  1. 数据存储限制:前端无法直接修改本地的form.json文件,所以提供了两种方案:
    • 纯前端用localStorage模拟数据持久化
    • 有后端的话,需要写接口(比如PHP)接收请求,修改服务器上的JSON文件
  2. 软删除可视化:渲染表格时新增了Status列,直观显示条目是否活跃,也可以改成只渲染is_active='true'的条目
  3. 事件委托:因为表格是动态生成的,用document.addEventListener绑定事件,确保新生成的按钮也能触发逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:25:21