document.getElementById("searchForm").submit is not a function

本文探讨了在使用JavaScript进行表单提交时遇到的一个常见错误:submit不是函数。作者通过实际案例分享了解决这一问题的经验,并揭示了表单中元素名称为'submit'时可能引发的问题。

今天在写代码的时候JS一直报上面这个错。搞了半天一直想不明白 。我看别的页面都是这样写了就是没有一点错。。

可能是写了一个晚上的代码。。头有点晕。。后来终于找到原因了。。浪费我两个小时啊。。杯具。。

 

有时候需要用javascript提交表单,这个时候我们会用javascript:userform.submit();可是我在这样做的时候怎么也提交不成功,报出javascript错误 Javascript Error: submit is not a function。百思不得其解,后来查阅资料才发现,在用userForm.submit() 提交表单的时候,表单里面不能有name="submit"的元素,否则在提交的 时候,该对象会和submit();方法发生混淆造成该错误!! 切记,切记!

文章转载于:http://ware.iteye.com/blog/1113250

<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>河北保尔后台管理系统</title> <script src="JS/util.js"></script> <link rel="stylesheet" href="css/index.css"> </head> <body> <!-- 顶部导航栏 --> <header class="top-bar"> <!-- 网站 logo --> <div class="logo"> <img src="https://oa.baoerkeji.com.cn/assets/logo-BOKAGd4s.png" alt="河北保尔"> <span style="font-weight: bold; font-size: 1.2rem;">河北保尔后台管理系统</span> </div> <!-- 时间和用户信息 --> <div class="time-user"> <span id="current-time">2025年09月25日 16:12:10</span> <span class="user">PGCHEF</span> </div> </header> <!-- 左侧功能导航栏 --> <aside class="sidebar"> <h1>后台管理系统</h1> <ul> <!-- 首页菜单 --> <li class="parent index active"> <span>首页</span> </li> <!-- 管理员管理菜单 --> <li class="parent"> <span>管理员管理</span> </li> <!-- 帖子管理菜单及子菜单 --> <li class="parent"> <span>帖子管理</span> <ul class="child"> <li>待审核帖子</li> <li>帖子列表</li> <li>帖子详情</li> <li>帖子删除</li> <li>帖子信息</li> </ul> </li> <!-- 审核管理菜单及子菜单 --> <li class="parent"> <span>审核管理</span> <ul class="child"> <li>审核帖子</li> <li>未审核通过的原因</li> </ul> </li> <!-- 用户管理菜单及子菜单 --> <li class="parent"> <span>用户管理</span> <ul class="child"> <li>查看用户信息</li> <li>拉黑操作</li> <li>查看评论及回复</li> </ul> </li> </ul> </aside> <!-- 主内容区 --> <main class="content"> <!-- 首页内容 --> <div id="home-section" class="content-section active"> <h2>系统概览</h2> <div class="welcome-img"> <img src="https://oa.baoerkeji.com.cn/assets/Hello-CZbGWvKg.png" alt="欢迎使用"> </div> </div> <!-- 管理员管理内容 --> <div id="admin-section" class="content-section"> <h2>管理员管理</h2> <div style="display: flex; justify-content: space-between; margin-bottom: 20px;"> <button class="btn btn-primary" id="add-admin-btn">添加管理员</button> <div> <input type="text" id="search-admin" placeholder="搜索管理员昵称..." style="padding: 8px; border: 1px solid #ddd; border-radius: 4px;"> <button class="btn btn-success" id="search-admin-btn">搜索</button> </div> </div> <div id="admin-table-container"> <table id="admin-table"> <thead> <tr> <th>ID</th> <th>账号</th> <th>昵称</th> <th>电话</th> <th>创建时间</th> <th>头像</th> <th>操作</th> </tr> </thead> <tbody id="admin-table-body"> <!-- 动态加载管理员数据 --> </tbody> </table> <div class="pagination" id="admin-pagination"> <!-- 分页按钮 --> </div> </div> </div> <!-- 帖子管理内容 --> <div id="post-section" class="content-section"> <h2>帖子管理</h2> <p>选择左侧子菜单查看具体内容</p> </div> <!-- 审核管理内容 --> <div id="audit-section" class="content-section"> <h2>审核管理</h2> <p>选择左侧子菜单查看具体内容</p> </div> <!-- 用户管理内容 --> <div id="user-section" class="content-section"> <h2>用户管理</h2> <p>选择左侧子菜单查看具体内容</p> </div> </main> <div id="admin-modal" class="modal"> <div class="modal-content"> <div class="modal-header"> <h3 id="modal-title">添加管理员</h3> <button class="modal-close" id="modal-close">×</button> </div> <form id="admin-form"> <input type="hidden" id="admin-id"> <div class="form-group"> <label for="admin-account">账号</label> <input type="text" id="admin-account" required> </div> <div class="form-group"> <label for="admin-password">密码</label> <input type="password" id="admin-password" required> </div> <div class="form-group"> <label for="admin-nickname">昵称</label> <input type="text" id="admin-nickname" required> </div> <div class="form-group"> <label for="admin-tel">电话</label> <input type="text" id="admin-tel"> </div> <div class="form-group"> <label for="admin-icon">头像</label> <input type="file" id="admin-icon" accept="image/*"> <div id="icon-preview" style="margin-top: 10px;"></div> </div> <div class="modal-footer"> <button type="button" class="btn" id="modal-cancel">取消</button> <button type="submit" class="btn btn-primary" id="modal-submit">保存</button> </div> </form> </div> </div> <script> window.onload = ()=>{ const nickName = localStorage.getItem('loginNickname'); const user = document.querySelector(".time-user .user"); if(nickName==null ){ console.log("没有信息,传入错误"); }else{ user.textContent = nickName; } } // 设置项目基础路径 const BASE_URL = '/PGtieba'; // 修复变量定义 const page = document.querySelector("#admin-pagination"); const tableBody = document.querySelector("#admin-table-body"); // 修复:使用tbody let pageIndex = 1; let pageSize = 5; let pageCount = 0; let searchKeyword = ""; // 页面加载完成后初始化 window.onload = function() { console.log("页面加载完成,BASE_URL:", BASE_URL); loadAdminList(); bindEvents(); }; // 修复后的绑定事件函数 function bindEvents() { // 搜索按钮事件 document.getElementById('search-admin-btn').addEventListener('click', function() { searchKeyword = document.getElementById('search-admin').value.trim(); pageIndex = 1; loadAdminList(); }); // 添加管理员按钮事件 document.getElementById('add-admin-btn').addEventListener('click', openAddModal); // 模态框关闭事件 document.getElementById('modal-close').addEventListener('click', function() { document.getElementById('admin-modal').style.display = 'none'; }); document.getElementById('modal-cancel').addEventListener('click', function() { document.getElementById('admin-modal').style.display = 'none'; }); // 表单提交事件 document.getElementById('admin-form').addEventListener('submit', function(e) { e.preventDefault(); const formData = new FormData(this); saveAdmin(formData); }); } //加载管理员列表函数 function loadAdminList() { let params = { pageIndex: pageIndex, pageSize: pageSize }; if (searchKeyword) { params.nickName = searchKeyword; } console.log("加载管理员列表,参数:", params); // 使用BASE_URL前缀 ajax.get(BASE_URL + '/admin/adminList', {data: JSON.stringify(params)}, function(response) { console.log("管理员列表响应:", response); if (response.code === 200) { const adminList = response.data.adminList; pageCount = response.data.pageCount; let content = ''; if (!adminList || adminList.length === 0) { content = '<tr><td colspan="7" style="text-align: center;">暂无数据</td></tr>'; } else { adminList.forEach(admin => { content += ` <tr> <td>${admin.adminId}</td> <td>${admin.account}</td> <td>${admin.nickName || '未设置'}</td> <td>${admin.tel || '未设置'}</td> <td>${admin.createtime || '未知'}</td> <td>${admin.icon ? `<img src="${admin.icon}" style="width: 50px; height: 50px;">` : '无'}</td> <td> <button class="btn btn-primary" onclick="editAdmin(${admin.adminId})">编辑</button> <button class="btn btn-danger" onclick="deleteAdmin(${admin.adminId})">删除</button> </td> </tr>`; }); } tableBody.innerHTML = content; updatePagination(); } else { alert('加载管理员列表失败: ' + response.msg); } }); } // 修复分页显示 function updatePagination() { if (page) { page.innerHTML = ` 共${pageCount}页,当前第${pageIndex}页 <button onclick="changePage(0)">首页</button> <button onclick="changePage(1)">上一页</button> <button onclick="changePage(2)">下一页</button> <button onclick="changePage(3)">尾页</button> `; checkButton(); } } // 检查分页按钮状态 function checkButton() { if (!page) return; let pageBtns = page.querySelectorAll("button"); if (pageIndex == 1 && pageIndex == pageCount) { pageBtns[0].disabled = true; pageBtns[1].disabled = true; pageBtns[2].disabled = true; pageBtns[3].disabled = true; } else if (pageIndex == 1) { pageBtns[0].disabled = true; pageBtns[1].disabled = true; pageBtns[2].disabled = false; pageBtns[3].disabled = false; } else if (pageIndex == pageCount) { pageBtns[0].disabled = false; pageBtns[1].disabled = false; pageBtns[2].disabled = true; pageBtns[3].disabled = true; } else { pageBtns[0].disabled = false; pageBtns[1].disabled = false; pageBtns[2].disabled = false; pageBtns[3].disabled = false; } } // 改变页码 function changePage(status) { switch (status) { case 0: pageIndex = 1; break; case 1: pageIndex -= 1; break; case 2: pageIndex += 1; break; case 3: pageIndex = pageCount; break; } loadAdminList(); } // 打开添加管理员模态框 function openAddModal() { document.getElementById('modal-title').textContent = '添加管理员'; document.getElementById('admin-form').reset(); document.getElementById('admin-id').value = ''; document.getElementById('icon-preview').innerHTML = ''; document.getElementById('admin-modal').style.display = 'flex'; } // 修复编辑管理员函数 function editAdmin(adminId) { console.log("编辑管理员:", adminId); ajax.get(BASE_URL + '/admin/getAdmin', {data: JSON.stringify({adminId: adminId})}, function(response) { console.log("管理员详情响应:", response); if (response.code === 200) { const admin = response.data; document.getElementById('modal-title').textContent = '编辑管理员'; document.getElementById('admin-id').value = admin.adminId; document.getElementById('admin-account').value = admin.account; document.getElementById('admin-nickname').value = admin.nickName || ''; document.getElementById('admin-tel').value = admin.tel || ''; document.getElementById('admin-password').value = ''; // 密码留空 if (admin.icon) { document.getElementById('icon-preview').innerHTML = `<img src="${admin.icon}" style="max-width: 100px; max-height: 100px;">`; } else { document.getElementById('icon-preview').innerHTML = ''; } document.getElementById('admin-modal').style.display = 'flex'; } else { alert('获取管理员信息失败: ' + response.msg); } }); } // 删除管理员 function deleteAdmin(adminId) { if (confirm('确定要删除这个管理员吗?')) { ajax.get(BASE_URL + '/admin/deleteList', {data: JSON.stringify({adminId: adminId})}, function(response) { if (response.code === 200) { alert('删除成功'); loadAdminList(); } else { alert('删除失败: ' + response.msg); } }); } } // 修复保存管理员函数 function saveAdmin(formData) { const adminData = { account: document.getElementById('admin-account').value, password: document.getElementById('admin-password').value, nickName: document.getElementById('admin-nickname').value, tel: document.getElementById('admin-tel').value }; const adminId = document.getElementById('admin-id').value; const iconFile = document.getElementById('admin-icon').files[0]; // 如果有头像文件,先上传头像 if (iconFile) { uploadIcon(iconFile, function(imageUrl, error) { if (error) { alert('头像上传失败: ' + error); return; } adminData.icon = imageUrl; saveAdminData(adminId, adminData); }); } else { saveAdminData(adminId, adminData); } } function saveAdminData(adminId, adminData) { if (adminId) { // 编辑操作 adminData.adminId = adminId; ajax.get(BASE_URL + '/admin/updateList', {data: JSON.stringify(adminData)}, function(response) { handleSaveResponse(response, '更新'); }); } else { // 添加操作 ajax.get(BASE_URL + '/admin/addAdmin', {data: JSON.stringify(adminData)}, function(response) { handleSaveResponse(response, '添加'); }); } } function handleSaveResponse(response, operation) { if (response.code === 200) { alert(operation + '成功'); document.getElementById('admin-modal').style.display = 'none'; if (operation === '添加') { pageIndex = 1; } loadAdminList(); } else { alert(operation + '失败: ' + response.msg); } } // 上传头像 function uploadIcon(file, callback) { const formData = new FormData(); formData.append('file', file); ajax.formData(BASE_URL + '/admin/uploadIcon', formData, function(response) { if (response.code === 200) { callback(response.data.imageUrl || response.data); } else { callback(null, response.msg || '上传失败'); } }); } // 实时更新时间 function updateTime() { const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, "0"); const day = String(now.getDate()).padStart(2, "0"); const hours = String(now.getHours()).padStart(2, "0"); const minutes = String(now.getMinutes()).padStart(2, "0"); const seconds = String(now.getSeconds()).padStart(2, "0"); const timeStr = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`; document.getElementById("current-time").textContent = timeStr; } updateTime(); setInterval(updateTime, 1000); // 页面加载完成后初始化 document.addEventListener('DOMContentLoaded', function() { const parents = document.querySelectorAll('.parent'); const childItems = document.querySelectorAll('.child li'); const contentSections = document.querySelectorAll('.content-section'); // 父菜单点击事件 parents.forEach(parent => { parent.addEventListener('click', function(e) { // 如果点击的是子菜单项,不处理父菜单点击 if (e.target.tagName === 'LI' && e.target.classList.contains('child')) return; if (e.target.parentElement && e.target.parentElement.classList.contains('child')) return; // 切换当前菜单的active状态 const isActive = this.classList.contains('active'); // 移除所有active类 parents.forEach(p => p.classList.remove('active')); contentSections.forEach(section => section.classList.remove('active')); // 如果之前不是active状态,则设置为active if (!isActive) { this.classList.add('active'); } // 显示对应内容区域 const index = Array.from(parents).indexOf(this); if (contentSections[index]) { contentSections[index].classList.add('active'); // 如果是管理员管理页面,加载数据 if (index === 1) { adminManager.loadAdminList(); } } }); }); // 子菜单点击事件 childItems.forEach(item => { item.addEventListener('click', function(e) { e.stopPropagation(); // 阻止事件冒泡 // 移除所有子菜单active类 childItems.forEach(li => li.classList.remove('active')); // 为当前子菜单添加active类 this.classList.add('active'); // 这里可以添加加载对应内容的逻辑 const parentSection = this.closest('.parent'); const sectionId = parentSection.querySelector('span').textContent.trim(); // 在实际应用中,这里应该加载对应的内容 console.log(`加载${sectionId}的"${this.textContent}"内容`); // 可以根据子菜单项显示不同的内容 showSubContent(this.textContent); }); }); // 显示子菜单内容的函数 function showSubContent(subMenuText) { // 获取当前激活的主内容区域 const activeSection = document.querySelector('.content-section.active'); // 根据子菜单文本更新内容 activeSection.innerHTML = ` <h2>${activeSection.querySelector('h2').textContent} - ${subMenuText}</h2> <p>这是 ${subMenuText} 的详细内容区域。</p> <p>在实际应用中,这里会加载对应的数据和管理功能。</p> <div style="margin-top: 20px;"> <button class="btn btn-primary">刷新数据</button> <button class="btn btn-success" style="margin-left: 10px;">导出报表</button> </div> `; } // 管理员管理相关事件绑定 document.getElementById('add-admin-btn').addEventListener('click', function() { adminManager.openAddModal(); }); document.getElementById('search-admin-btn').addEventListener('click', function() { adminManager.searchKeyword = document.getElementById('search-admin').value; adminManager.loadAdminList(1); }); document.getElementById('search-admin').addEventListener('keypress', function(e) { if (e.key === 'Enter') { adminManager.searchKeyword = this.value; adminManager.loadAdminList(1); } }); // 模态框相关事件 document.getElementById('modal-close').addEventListener('click', function() { document.getElementById('admin-modal').style.display = 'none'; }); document.getElementById('modal-cancel').addEventListener('click', function() { document.getElementById('admin-modal').style.display = 'none'; }); // 表单提交 document.getElementById('admin-form').addEventListener('submit', function(e) { e.preventDefault(); const formData = new FormData(this); const iconFile = document.getElementById('admin-icon').files[0]; if (iconFile) { // 如果有头像文件,先上传头像 adminManager.uploadIcon(iconFile, function(result, error) { if (error) { alert('头像上传失败: ' + error); return; } // 头像上传成功后保存管理员信息 formData.set('icon', result); adminManager.saveAdmin(formData); }); } else { // 没有头像文件,直接保存管理员信息 adminManager.saveAdmin(formData); } }); // 头像预览 document.getElementById('admin-icon').addEventListener('change', function(e) { const file = e.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = function(e) { document.getElementById('icon-preview').innerHTML = `<img src="${e.target.result}" style="max-width: 100px; max-height: 100px; border-radius: 4px;">`; }; reader.readAsDataURL(file); } }); // 默认激活首页 document.querySelector('.parent.index').classList.add('active'); document.querySelector('#home-section').classList.add('active'); }); </script> </body> </html>package com.yyq.servlet; import com.alibaba.fastjson.JSONObject; import com.yyq.dao.AdminDao; import com.yyq.entity.Admin; import com.yyq.util.R; import com.yyq.util.ResultCode; import com.yyq.util.UploadUtil; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.MultipartConfig; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; @WebServlet(urlPatterns = "/admin/*") @MultipartConfig(maxFileSize = 10485760,maxRequestSize = 10485760) public class AdminManagementServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static AdminDao adminDao = new AdminDao(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json;charset=utf-8"); resp.setCharacterEncoding("UTF-8"); String path = req.getPathInfo(); if (path == null) { sendError(resp, "路径不能为空"); return; } path = path.substring(1); // 去掉开头的/ System.out.println("接收到请求,路径: " + path); System.out.println("查询参数: " + req.getQueryString()); String res = null; PrintWriter out = null; try { out = resp.getWriter(); switch (path) { case "adminList": { System.out.println("---------管理员列表-----------"); String data = req.getParameter("data"); System.out.println("接收到的data参数: " + data); Map<String,Object> map = new HashMap<>(); if(data != null && !data.isEmpty()) { map = JSONObject.parseObject(data, Map.class); } int pageIndex = map.get("pageIndex") != null ? Integer.parseInt(map.get("pageIndex").toString()) : 1; int pageSize = map.get("pageSize") != null ? Integer.parseInt(map.get("pageSize").toString()) : 5; map.put("pageIndex", pageIndex); map.put("pageSize", pageSize); List<Admin> adminList = adminDao.adminList(map); int pageCount = adminDao.pageCount(pageSize); Map<String,Object> resultMap = new HashMap<>(); resultMap.put("pageCount", pageCount); resultMap.put("adminList", adminList); res = R.ok(resultMap).toJSONString(); break; } case "addAdmin": { System.out.println("---------添加管理员-------------"); String data = req.getParameter("data"); System.out.println("接收到的data参数: " + data); if(data == null || data.isEmpty()) { res = R.er(ResultCode.PARAM_ERROR, "数据参数为空").toJSONString(); break; } Admin admin = JSONObject.parseObject(data, Admin.class); System.out.println("解析后的admin对象: " + admin); int i = adminDao.addAdmin(admin); res = i > 0 ? R.ok().toJSONString() : R.er(ResultCode.ERROR, "添加管理员失败").toJSONString(); break; } case "deleteList": { System.out.println("----------删除管理员-------------"); String data = req.getParameter("data"); if(data != null && !data.isEmpty()) { Map<String, Object> map = JSONObject.parseObject(data, Map.class); int adminId = Integer.parseInt(map.get("adminId").toString()); int i = adminDao.deleteAdmin(adminId); res = i > 0 ? R.ok().toJSONString() : R.er(ResultCode.ERROR, "删除失败").toJSONString(); } else { res = R.er(ResultCode.PARAM_ERROR, "参数错误").toJSONString(); } break; } case "updateList": { System.out.println("-------更新管理员-------------"); String data = req.getParameter("data"); if(data != null && !data.isEmpty()) { Admin admin = JSONObject.parseObject(data, Admin.class); int row = adminDao.updateAdmin(admin); res = row > 0 ? R.ok().toJSONString() : R.er(ResultCode.ERROR, "更新失败").toJSONString(); } else { res = R.er(ResultCode.PARAM_ERROR, "没有收到前端参数").toJSONString(); } break; } case "uploadIcon": { System.out.println("---------上传头像-----------"); String imagepath = UploadUtil.uploadFile(req); System.out.println("图片的路径是: " + imagepath); Map<String, String> result = new HashMap<>(); result.put("imageUrl", imagepath); res = R.ok(result).toJSONString(); break; } case "getAdmin": { System.out.println("---------获取管理员详情-----------"); String data = req.getParameter("data"); if(data != null && !data.isEmpty()) { Map<String, Object> map = JSONObject.parseObject(data, Map.class); int adminId = Integer.parseInt(map.get("adminId").toString()); // 这里需要实现getAdminById方法 Admin admin = adminDao.getAdminById(adminId); if(admin != null) { res = R.ok(admin).toJSONString(); } else { res = R.er(ResultCode.ERROR, "管理员不存在").toJSONString(); } } else { res = R.er(ResultCode.PARAM_ERROR, "参数错误").toJSONString(); } break; } default: { res = R.er(ResultCode.ERROR, "未知操作: " + path).toJSONString(); break; } } // 确保有响应 if (res == null) { res = R.er(ResultCode.ERROR, "操作未完成").toJSONString(); } System.out.println("返回响应: " + res); out.print(res); } catch (Exception e) { e.printStackTrace(); if (out != null) { out.print(R.er(ResultCode.ERROR, "服务器异常: " + e.getMessage()).toJSONString()); } } } private void sendError(HttpServletResponse resp, String message) throws IOException { resp.setStatus(400); PrintWriter out = resp.getWriter(); out.print(R.er(ResultCode.ERROR, message).toJSONString()); out.flush(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); // 或者实现独立的POST处理 } }查看一下我的搜索功能为什么出 问题
最新发布
10-10
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>总订单完成状况</title> <style> :root{ --bg:#f5faff; --panel:#fff; --border:#cce7ff; --primary:#3ca9ff; --primary-dark:#0077e6; --primary-light:#e6f4ff; --text:#003366; --text-light:#0077e6; --shadow:rgba(60,169,255,.12); } body{margin:0;background:var(--bg);font-family:"Segoe UI",Arial,"PingFang SC","Microsoft YaHei",sans-serif} .status-container{max-width:98%;margin:22px auto;background:var(--panel);border:1px solid var(--border);padding:22px 18px 30px 18px;border-radius:12px;box-shadow:0 6px 30px var(--shadow);position:relative} .status-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:18px;background:var(--bg)} .status-header h3{color:var(--text-light);letter-spacing:2px} .status-header .btns{display:flex;gap:12px} .btn{padding:7px 18px;border:none;border-radius:4px;font-size:15px;cursor:pointer;background:var(--primary);color:#fff;transition:background .2s} .btn:hover{background:var(--primary-dark)} .btn.modify{background:var(--primary-light);color:var(--text)} .btn.modify:hover{background:var(--primary-dark);color:#fff} .search-box{display:flex;align-items:center;gap:8px} .search-box input{height:32px;border:1px solid var(--primary);border-radius:4px;padding:0 10px;font-size:14px;background:#fff;color:var(--text)} table{width:100%;border-collapse:collapse;font-size:14px;color:var(--text)} thead{background-color:var(--primary-light);color:var(--text)} th,td{border:1px solid var(--border);padding:9px 7px;text-align:center} th{background:var(--primary-light);color:var(--text)} tr:nth-child(even){background:var(--bg)} .tag{border-radius:10px;padding:2px 10px;font-size:13px;display:inline-block} .tag-success{background:#d0ffd0;color:#006100} .tag-danger{background:#ffecec;color:#c00000;cursor:pointer} td:last-child{white-space:nowrap;min-width:120px} /* 弹窗 */ .modal-mask{position:fixed;left:0;top:0;width:100%;height:100%;background:rgba(0,119,230,.2);z-index:999;display:none} .modal{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);background:#fff;min-width:360px;border-radius:8px;box-shadow:0 8px 32px rgba(60,169,255,.15);padding:22px;z-index:1000;display:none} .modal-title{font-weight:bold;font-size:1.18rem;color:var(--primary-dark);margin-bottom:19px} .modal-form-row{margin-bottom:13px;display:flex;align-items:center} .modal-form-row label{width:86px;color:var(--text-light);font-size:14px} .modal-form-row input,.modal-form-row select{flex:1;height:28px;padding:0 7px;border:1px solid var(--primary);border-radius:4px;background:var(--bg);color:var(--text)} .modal-btns{text-align:right;margin-top:18px} .modal-btns .btn{margin-left:12px;background:var(--primary)} /* 分页 */ .pager-box{display:flex;align-items:center;gap:8px;position:absolute;right:22px;bottom:-80px;background:var(--primary-light);padding:6px 10px;border-radius:6px;box-shadow:0 2px 8px var(--shadow);font-size:14px;color:var(--text-light)} .pager-label input{width:46px;height:24px;text-align:center;border:1px solid var(--primary);border-radius:4px;margin:0 4px;background:#fff;color:var(--text-light)} </style> </head> <body> <div class="status-container"> <div class="status-header"> <h3>总订单完成状况</h3> <div class="btns"> <div class="search-box"> <input type="text" id="searchInput" placeholder="订单编号、产品名称...关键词查询"> <button class="btn" onclick="searchOrders()">查询</button> </div> <button class="btn" onclick="openAddModal()">增加</button> </div> </div> <table> <thead> <tr> <th>序号</th><th>销售类型</th><th>订单编号</th><th>产品编号</th><th>产品名称</th> <th>订单数量</th><th>GTM要求交期</th><th>订单评审出货日期</th> <th>电子料齐套</th><th>组装料齐套</th> <th>SMT累计出货</th><th>SMT欠订单数</th><th>SMT工厂</th> <th>组装累计出货</th><th>组装欠订单数</th><th>组装工厂</th> <th>结单状况</th><th>备注</th><th>操作</th> </tr> </thead> <tbody id="orderTableBody"><tr><td colspan="19">加载中...</td></tbody> </table> <div id="pagerBox" class="pager-box"> <button class="btn" id="btnPrev" onclick="prevPage()">上一页</button> <label class="pager-label"> 第<input type="number" id="pageInput" min="1" max="1" value="1" onkeydown="if(event.key==='Enter') jumpToPage()">页 / 共<span id="totalPages">1</span>页 </label> <button class="btn" id="btnNext" onclick="nextPage()">下一页</button> <button class="btn modify" onclick="jumpToPage()">跳转</button> </div> </div> <!-- 订单弹窗 --> <div class="modal-mask" id="modalMask"></div> <div class="modal" id="modalBox"> <div class="modal-title" id="modalTitle">新增订单</div> <form id="modalForm"> <div class="modal-form-row"><label>销售类型</label><input name="saleType" required></div> <div class="modal-form-row"><label>订单编号</label><input name="orderNo" required></div> <div class="modal-form-row"><label>产品编号</label><input name="productNo" required></div> <div class="modal-form-row"><label>产品名称</label><input name="productName" required></div> <div class="modal-form-row"><label>订单数量</label><input type="number" name="orderQuantity" required></div> <div class="modal-form-row"><label>GTM交期</label><input type="date" name="gtmDueDate"></div> <div class="modal-form-row"><label>评审出货日期</label><input type="date" name="reviewShipDate"></div> <div class="modal-form-row"><label>电子料齐套</label> <select name="materialElectronic"><option value="1">齐套</option><option value="0">未齐套</option></select></div> <div class="modal-form-row"><label>组装料齐套</label> <select name="materialAssembly"><option value="1">齐套</option><option value="0">未齐套</option></select></div> <div class="modal-form-row"><label>SMT累计出货</label><input type="number" name="smtShippedQty"></div> <div class="modal-form-row"><label>SMT欠订单数</label><input type="number" name="smtOwedQty"></div> <div class="modal-form-row"><label>SMT工厂</label><input name="smtFactory"></div> <div class="modal-form-row"><label>组装累计出货</label><input type="number" name="assemblyShippedQty"></div> <div class="modal-form-row"><label>组装欠订单数</label><input type="number" name="assemblyOwedQty"></div> <div class="modal-form-row"><label>组装工厂</label><input name="assemblyFactory"></div> <div class="modal-form-row"><label>接单状况</label><input name="receiveStatus"></div> <div class="modal-form-row"><label>备注</label><input name="remark"></div> <div class="modal-btns"> <button type="button" class="btn" onclick="closeModal()">取消</button> <button type="submit" class="btn modify" id="modalSubmitBtn">保存</button> </div> </form> </div> <!-- 通用 BOM 详情弹窗 --> <div class="modal-mask" id="bomModalMask"></div> <div class="modal" id="bomModalBox"> <div class="modal-title" id="bomModalTitle">BOM 齐套详情</div> <form id="bomModalForm"> <input type="hidden" id="bomType"> <input type="hidden" id="bomOrderNo"> <div class="modal-form-row"> <label>BOM 版本</label> <select id="bomVersionSelect" required></select> </div> <!-- 物料编码 --> <div class="modal-form-row"> <label>物料编码</label> <input type="text" id="materialCode" required placeholder="请输入物料编码"> </div> <!-- 物料名称 --> <div class="modal-form-row"> <label>物料名称</label> <input type="text" id="materialName" required placeholder="如:贴片电阻"> </div> <!-- 规格 --> <div class="modal-form-row"> <label>规格</label> <input type="text" id="specification" placeholder="如:0603 1KΩ ±1%"> </div> <!-- 技术参数 --> <div class="modal-form-row"> <label>技术参数</label> <input type="text" id="technicalParam" placeholder="如:阻值范围/温度系数"> </div> <!-- 参数值 --> <div class="modal-form-row"> <label>参数值</label> <input type="text" id="paramValue" placeholder="如:1KΩ/±100ppm/℃"> </div> <!-- 用量 --> <div class="modal-form-row"> <label>用量</label> <input type="number" id="quantity" required min="1" placeholder="单个产品所需数量"> </div> <!-- 制造商 --> <div class="modal-form-row"> <label>制造商</label> <input type="number" id="manufacturerSelect" required min="1" placeholder="单个产品所需数量"> </div> <!-- 制造商料号 --> <div class="modal-form-row"> <label>制造商料号</label> <input type="text" id="mpn" required placeholder="如:RC0603FR-071KL"> </div> <div class="modal-btns"> <button type="button" class="btn" onclick="closeBomModal()">取消</button> <button type="submit" class="btn modify">保存</button> </div> </form> </div> <!-- 电子料齐套弹窗 --> <div class="modal-mask" id="eBomModalMask"></div> <div class="modal" id="eBomModalBox"> <div class="modal-title">电子料齐套详情</div> <form id="eBomModalForm"> <div class="modal-form-row"><label>订单编号</label><input id="eBomOrderNo" readonly></div> <div class="modal-form-row"><label>BOM版本</label><select id="eBomVersionSelect" required></select></div> <div class="modal-form-row"><label>订单数量</label><input type="number" id="eBomOrderQty" min="1" required></div> <div class="modal-btns"> <button type="button" class="btn" onclick="closeEBomModal()">取消</button> <button type="submit" class="btn modify">保存</button> </div> </form> </div> <script> let editingId = null, allOrders = [], currentPage = 1, totalPages = 1; const eBomQtyCache = {}; // 已录入电子料齐套数量缓存 async function request(url, method='GET', body=null){ const res = await fetch(url, { method, headers: body ? {'Content-Type':'application/json'} : {}, body: body ? JSON.stringify(body) : undefined }); return res.json(); } async function loadOrders(keyword, page){ const tbody=document.getElementById('orderTableBody'); tbody.innerHTML='<tr><td colspan="19">加载中...</td></tr>'; try{ let url=`/api/orders?page=${page}&size=10`; if(keyword) url+=`&keyword=${encodeURIComponent(keyword)}`; const data=await request(url); allOrders=data.records; renderOrders(data.records); currentPage=data.current; totalPages=data.pages; updatePager(); }catch(e){ tbody.innerHTML='<tr><td colspan="19">加载失败</td></tr>'; } } function renderOrders(data){ const tbody=document.getElementById('orderTableBody'); if(!data.length){ tbody.innerHTML='<tr><td colspan="19">暂无数据</td></tr>'; return; } tbody.innerHTML=data.map(r=>` <tr> <td>${r.id}</td><td>${r.saleType||'-'}</td><td>${r.orderNo||'-'}</td><td>${r.productNo||'-'}</td><td>${r.productName||'-'}</td> <td>${r.orderQuantity??'-'}</td><td>${r.gtmDueDate||'-'}</td><td>${r.reviewShipDate||'-'}</td> <!-- 电子料齐套列:未齐套可点击 --> <td> <span class="tag ${r.materialElectronic?'tag-success':'tag-danger'}" style="cursor:${r.materialElectronic?'default':'pointer'}" onclick="${!r.materialElectronic?`openEBomDetailModal('${r.orderNo}',${r.orderQuantity||0})`:''}"> ${r.materialElectronic?'齐套':'未齐套'} </span> <button class="btn modify" style="font-size:12px;padding:2px 8px" onclick="openEBomDetailTable('${r.orderNo}')">详情</button> </td> <!-- 组装料齐套列:保持原状 --> <td> <span class="tag ${r.materialAssembly?'tag-success':'tag-danger'}"> ${r.materialAssembly?'齐套':'未齐套'} </span> <button class="btn modify" style="font-size:12px;padding:2px 8px" onclick="openBomDetail('assembly','${r.orderNo}',${r.orderQuantity||0})"> 详情 </button> </td> <td>${r.smtShippedQty??'-'}</td><td>${r.smtOwedQty??'-'}</td><td>${r.smtFactory||'-'}</td> <td>${r.assemblyShippedQty??'-'}</td><td>${r.assemblyOwedQty??'-'}</td><td>${r.assemblyFactory||'-'}</td> <td>${r.receiveStatus||'-'}</td><td>${r.remark||'-'}</td> <td> <button class="btn modify" onclick="openEditModal(${r.id})">修改</button> <button class="btn" style="margin-left:6px;background:#f56c6c" onclick="deleteOrder(${r.id})">删除</button> </td> </tr>`).join(''); } function searchOrders(){loadOrders(document.getElementById('searchInput').value.trim(),1);} function updatePager(){ const p=document.getElementById('pageInput'); p.max=totalPages; p.value=currentPage; document.getElementById('totalPages').textContent=totalPages; document.getElementById('btnPrev').disabled=currentPage<=1; document.getElementById('btnNext').disabled=currentPage>=totalPages; } function jumpToPage(){ const v=parseInt(document.getElementById('pageInput').value,10); if(v>=1&&v<=totalPages) loadOrders(document.getElementById('searchInput').value.trim(),v); } function prevPage(){if(currentPage>1) loadOrders(document.getElementById('searchInput').value.trim(),currentPage-1);} function nextPage(){if(currentPage<totalPages) loadOrders(document.getElementById('searchInput').value.trim(),currentPage+1);} /* 订单弹窗 */ function openAddModal(){editingId=null;resetModal('新增订单');} function openEditModal(id){ editingId=id; const r=allOrders.find(r=>r.id===id); resetModal('修改订单',r); } function resetModal(title,data={}){ document.getElementById('modalTitle').textContent=title; const f=document.getElementById('modalForm'); f.reset(); for(const k in data) if(f[k]!==undefined) f[k].value=data[k]; document.getElementById('modalMask').style.display='block'; document.getElementById('modalBox').style.display='block'; } function closeModal(){ document.getElementById('modalMask').style.display='none'; document.getElementById('modalBox').style.display='none'; } document.getElementById('modalMask').onclick=closeModal; document.getElementById('modalForm').onsubmit=async e=>{ e.preventDefault(); const fd=new FormData(e.target); const data=Object.fromEntries(fd); data.materialElectronic=data.materialElectronic==='1'; data.materialAssembly=data.materialAssembly==='1'; ['orderQuantity','smtShippedQty','smtOwedQty','assemblyShippedQty','assemblyOwedQty'] .forEach(k=>{if(data[k])data[k]=Number(data[k]);}); try{ const url=editingId?`/api/orders/${editingId}`:'/api/orders'; const meth=editingId?'PUT':'POST'; await request(url,meth,data); closeModal(); loadOrders('',currentPage); }catch{alert('保存失败');} }; async function deleteOrder(id){ if(!confirm(`确定删除订单 ${id} 吗?`)) return; try{ await request(`/api/orders/${id}`,'DELETE'); loadOrders(document.getElementById('searchInput').value.trim(),currentPage); }catch{alert('删除失败');} } /* ========= 通用 BOM 弹窗 ========= */ function openBomDetail(type, orderNo, orderQty){ document.getElementById('bomType').value = type; // electronic / assembly document.getElementById('bomOrderNo').value = orderNo; document.getElementById('bomModalTitle').textContent = (type === 'electronic' ? '电子料' : '组装料') + '齐套详情'; /* 拉取或初始化数据 */ fetchBomDetail(type, orderNo).then(data=>{ fillBomModal(data, orderQty); document.getElementById('bomModalMask').style.display='block'; document.getElementById('bomModalBox').style.display='block'; }); } async function fetchBomDetail(type, orderNo){ // 调用后端接口,返回 {bomVersion, orderQty, needQty, oweQty} const res = await request(`/api/bom_detail/${type}/${orderNo}`); return res || {}; } function fillBomModal(data, orderQty){ /* 版本下拉 */ const sel=document.getElementById('bomVersionSelect'); sel.innerHTML=''; const versions = JSON.parse(localStorage.getItem('eBomVersions')||'[]'); versions.forEach(v=>{ const opt=document.createElement('option'); opt.value=opt.textContent=v; if(v===data.bomVersion) opt.selected=true; sel.appendChild(opt); }); document.getElementById('bomOrderQty').value = data.orderQty ?? orderQty; document.getElementById('bomNeedQty').value = data.needQty ?? 0; document.getElementById('bomOweQty').value = data.oweQty ?? 0; } function closeBomModal(){ document.getElementById('bomModalMask').style.display='none'; document.getElementById('bomModalBox').style.display='none'; } document.getElementById('bomModalMask').onclick = closeBomModal; /* 保存 */ document.getElementById('bomModalForm').addEventListener('submit', async e=>{ e.preventDefault(); const type = document.getElementById('bomType').value; const orderNo= document.getElementById('bomOrderNo').value; const payload = { bomVersion : document.getElementById('bomVersionSelect').value, orderQty : Number(document.getElementById('bomOrderQty').value), needQty : Number(document.getElementById('bomNeedQty').value), oweQty : Number(document.getElementById('bomOweQty').value) }; try{ await request(`/api/bom_detail/${type}/${orderNo}`, 'POST', payload); alert('保存成功'); closeBomModal(); }catch{ alert('保存失败'); } }); /* 电子料齐套弹窗 */ function openEBomDetailModal(orderNo,orderQty){ document.getElementById('eBomOrderNo').value=orderNo; const cached=eBomQtyCache[orderNo]||0; document.getElementById('eBomOrderQty').value=cached; document.getElementById('eBomOrderQty').min=cached; const sel=document.getElementById('eBomVersionSelect'); sel.innerHTML=''; const versions=JSON.parse(localStorage.getItem('eBomVersions')||'[]'); if(!versions.length){alert('请先打开“电子料 BOM 明细”页面以同步 BOM 版本数据');return;} versions.forEach(v=>{ const opt=document.createElement('option'); opt.value=opt.textContent=v; sel.appendChild(opt); }); document.getElementById('eBomModalMask').style.display='block'; document.getElementById('eBomModalBox').style.display='block'; } function closeEBomModal(){ document.getElementById('eBomModalMask').style.display='none'; document.getElementById('eBomModalBox').style.display='none'; } document.getElementById('eBomModalMask').onclick=closeEBomModal; document.getElementById('eBomModalForm').addEventListener('submit',async e=>{ e.preventDefault(); const orderNo=document.getElementById('eBomOrderNo').value.trim(); const bomVersion=document.getElementById('eBomVersionSelect').value; const qty=Number(document.getElementById('eBomOrderQty').value); const cached=eBomQtyCache[orderNo]||0; if(qty<cached){alert('订单数量只能增加,不能减少!');return;} try{ await request('/api/electronic_bom_detail','POST',{orderNo,bomVersion,orderQty:qty}); eBomQtyCache[orderNo]=qty; alert('保存成功'); closeEBomModal(); }catch{alert('保存失败');} }); loadOrders('',1); </script> </body> </html>能不能给我当点击未齐套时页面跳转的具体流程,当我单击详情时该怎么实现页面跳转
07-20
// 全局变量 const API_BASE = 'jsp/'; // DOM加载完成后执行 document.addEventListener('DOMContentLoaded', function() { // 根据页面ID加载不同内容 const bodyId = document.body.id; if (bodyId === 'home-page') { loadQuestions(); } else if (bodyId === 'question-detail-page') { const urlParams = new URLSearchParams(window.location.search); const questionId = urlParams.get('id'); if (questionId) { document.getElementById('question-id').value = questionId; loadQuestionDetail(questionId); loadAnswers(questionId); } else { showMessage('无效的问题ID', 'error'); setTimeout(() => { window.location.href = 'index.html'; }, 2000); } } else if (bodyId === 'post-question-page') { setupCharCounters(); } // 设置表单提交事件 setupFormHandlers(); }); // 设置字符计数器 function setupCharCounters() { const titleInput = document.getElementById('title'); const contentInput = document.getElementById('content'); const answerContentInput = document.getElementById('answer-content'); if (titleInput) { titleInput.addEventListener('input', function() { document.getElementById('title-char-count').textContent = this.value.length; }); } if (contentInput) { contentInput.addEventListener('input', function() { document.getElementById('content-char-count').textContent = this.value.length; }); } if (answerContentInput) { answerContentInput.addEventListener('input', function() { document.getElementById('answer-char-count').textContent = this.value.length; }); } } // 加载问题列表 function loadQuestions() { const questionList = document.getElementById('question-list'); if (!questionList) return; showLoader(questionList); fetch(API_BASE + 'get_questions.jsp') .then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.json(); }) .then(data => { hideLoader(questionList); if (data.error) { showMessage(data.error, 'error'); return; } if (data.length === 0) { questionList.innerHTML = ` <div class="card empty-state"> <p>暂无问题</p> <p><a href="post_question.html" class="btn">提出第一个问题</a></p> </div> `; return; } let html = ''; data.forEach(question => { html += ` <div class="card question-item" onclick="window.location.href='question_detail.html?id=${question.id}'"> <h2 class="question-title"> ${escapeHtml(question.title)} </h2> <div class="question-content"> ${escapeHtml(question.content.length > 150 ? question.content.substring(0, 150) + '...' : question.content)} </div> <div class="question-meta"> <span class="meta-item"> <i class="icon-time"></i> ${formatDate(question.create_time)} </span> </div> </div> `; }); questionList.innerHTML = html; }) .catch(error => { hideLoader(questionList); showMessage('加载问题失败: ' + error.message, 'error'); console.error('Error:', error); }); } // 加载问题详情 function loadQuestionDetail(questionId) { const questionDetail = document.getElementById('question-detail'); if (!questionDetail) return; showLoader(questionDetail); fetch(API_BASE + 'get_question_detail.jsp?id=' + encodeURIComponent(questionId)) .then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.json(); }) .then(data => { hideLoader(questionDetail); if (data.error) { showMessage(data.error, 'error'); if (data.error.includes('不存在')) { setTimeout(() => { window.location.href = 'index.html'; }, 2000); } return; } const html = ` <div class="card question-detail"> <h1 class="question-title">${escapeHtml(data.title)}</h1> <div class="question-content"> ${escapeHtml(data.content).replace(/\n/g, '<br>')} </div> <div class="question-meta"> <span class="meta-item"> <i class="icon-time"></i> ${formatDate(data.create_time)} </span> </div> </div> `; questionDetail.innerHTML = html; document.title = `${data.title} - 简易论坛`; }) .catch(error => { hideLoader(questionDetail); showMessage('加载问题详情失败: ' + error.message, 'error'); console.error('Error:', error); }); } // 加载回答列表 function loadAnswers(questionId) { const answerList = document.getElementById('answer-list'); const answerCount = document.getElementById('answer-count'); if (!answerList) return; showLoader(answerList); fetch(API_BASE + 'get_answers.jsp?question_id=' + encodeURIComponent(questionId)) .then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.json(); }) .then(data => { hideLoader(answerList); if (data.error) { showMessage(data.error, 'error'); return; } if (answerCount) { answerCount.textContent = `${data.length} 个回答`; } if (data.length === 0) { answerList.innerHTML = ` <div class="card empty-state"> <p>暂无回答</p> <p>成为第一个回答者吧!</p> </div> `; return; } let html = ''; data.forEach(answer => { html += ` <div class="card answer-item"> <div class="answer-content"> ${escapeHtml(answer.content).replace(/\n/g, '<br>')} </div> <div class="answer-meta"> <span class="meta-item"> <i class="icon-time"></i> ${formatDate(answer.create_time)} </span> </div> </div> `; }); answerList.innerHTML = html; }) .catch(error => { hideLoader(answerList); showMessage('加载回答失败: ' + error.message, 'error'); console.error('Error:', error); }); } // 设置表单处理程序 function setupFormHandlers() { // 提问表单 const questionForm = document.getElementById('question-form'); if (questionForm) { questionForm.addEventListener('submit', function(e) { e.preventDefault(); submitQuestionForm(this); }); } // 回答表单 const answerForm = document.getElementById('answer-form'); if (answerForm) { answerForm.addEventListener('submit', function(e) { e.preventDefault(); submitAnswerForm(this); }); } } // 提交问题表单 function submitQuestionForm(form) { const formData = new FormData(form); const submitBtn = form.querySelector('button[type="submit"]'); const originalText = submitBtn.textContent; // 禁用提交按钮并显示加载状态 submitBtn.disabled = true; submitBtn.textContent = '提交中...'; fetch(API_BASE + 'do_post_question.jsp', { method: 'POST', body: formData }) .then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.json(); }) .then(data => { // 恢复提交按钮 submitBtn.disabled = false; submitBtn.textContent = originalText; if (data.success) { showMessage('问题提交成功!', 'success'); setTimeout(() => { if (data.id) { window.location.href = 'question_detail.html?id=' + data.id; } else { window.location.href = 'index.html'; } }, 1500); } else { showMessage('提交失败: ' + (data.error || '未知错误'), 'error'); } }) .catch(error => { // 恢复提交按钮 submitBtn.disabled = false; submitBtn.textContent = originalText; showMessage('提交失败: ' + error.message, 'error'); console.error('Error:', error); }); } // 提交回答表单 function submitAnswerForm(form) { const formData = new FormData(form); const submitBtn = form.querySelector('button[type="submit"]'); const originalText = submitBtn.textContent; // 获取问题ID const questionId = formData.get('question_id'); // 禁用提交按钮并显示加载状态 submitBtn.disabled = true; submitBtn.textContent = '提交中...'; fetch(API_BASE + 'do_post_answer.jsp', { method: 'POST', body: formData }) .then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.json(); }) .then(data => { // 恢复提交按钮 submitBtn.disabled = false; submitBtn.textContent = originalText; if (data.success) { showMessage('回答提交成功!', 'success'); form.reset(); document.getElementById('answer-char-count').textContent = '0'; // 重新加载回答列表 if (questionId) { loadAnswers(questionId); } } else { showMessage('提交失败: ' + (data.error || '未知错误'), 'error'); } }) .catch(error => { // 恢复提交按钮 submitBtn.disabled = false; submitBtn.textContent = originalText; showMessage('提交失败: ' + error.message, 'error'); console.error('Error:', error); }); } // 显示消息 function showMessage(message, type) { // 移除现有的消息 const existingAlert = document.querySelector('.alert'); if (existingAlert) { existingAlert.remove(); } // 创建新消息 const alert = document.createElement('div'); alert.className = `alert alert-${type}`; alert.textContent = message; // 将消息插入到页面中 const container = document.querySelector('.container') || document.body; container.insertBefore(alert, container.firstChild); // 5秒后自动消失 setTimeout(() => { if (alert.parentNode) { alert.remove(); } }, 5000); } // 显示加载器 function showLoader(container) { const loader = document.createElement('div'); loader.className = 'loader'; container.innerHTML = ''; container.appendChild(loader); } // 隐藏加载器 function hideLoader(container) { const loader = container.querySelector('.loader'); if (loader) { loader.remove(); } } // 转义HTML特殊字符 function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } // 格式化日期 function formatDate(dateString) { try { const date = new Date(dateString); if (isNaN(date.getTime())) { return dateString; } return date.toLocaleString('zh-CN'); } catch (e) { return dateString; } } 这是完整的js代码,如何修改
09-16
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值