毕业设计:模态框触发GDrive与MySQL文件删除时误删首条记录求助
问题根源分析
你的问题核心在于重复使用相同的id属性,以及模态框未关联当前要删除的记录ID:
- 每一行的隐藏删除按钮都使用了
removeFromDrive和removeDb这两个重复id,而document.getElementById()只会返回DOM中第一个匹配该id的元素,所以无论点击哪一行的删除按钮,最终都会触发第一行的删除操作。 - 全局模态框没有记录当前用户要删除的文件ID,导致无法准确传递参数到删除函数。
解决方案
我们可以去掉冗余的隐藏按钮,直接在点击删除按钮时存储当前文件ID,模态框确认后直接调用删除函数,彻底解决ID冲突问题:
1. 修改表格操作列代码
移除重复id的隐藏按钮,给删除按钮添加存储当前文件ID的逻辑:
<td> <button class="btn btn-primary btn-sm" onclick="window.location.href='<?php echo $rows['file_viewLink'];?>'"><span class="glyphicon glyphicon-eye-open"></span> View</button> <button class="btn btn-success btn-sm" onclick="window.location.href='<?php echo $rows['file_downloadLink'];?>'"><span class="glyphicon glyphicon-download-alt"></span> Download</button> <!-- 点击时先存储当前文件ID,再触发认证和模态框 --> <button class="btn btn-danger btn-delete" type="button" onclick="setCurrentFileId('<?php echo $rows['file_id'];?>'); handleAuthClick()" data-toggle="modal" data-target="#modal_remove"><span class="glyphicon glyphicon-trash"></span> Remove</button> </td>
2. 修改模态框确认按钮
将原来的触发隐藏按钮的逻辑改为直接调用确认删除函数:
<div class="modal fade" id="modal_remove" aria-hidden="true" role="dialog"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title">System</h3> </div> <div class="modal-body"> <h4 class="text-danger">Are you sure you want to remove this file?</h4> </div> <div class="modal-footer"> <a type="button" class="btn btn-success" data-dismiss="modal">No</a> <!-- 调用确认删除函数 --> <button type="button" class="btn btn-danger" onclick="confirmDelete()" data-dismiss="modal">Yes</button> </div> </div> </div> </div>
3. 更新JavaScript逻辑
添加全局变量存储当前文件ID,替换原来的触发按钮逻辑为直接调用删除函数:
// 全局变量存储当前要删除的文件ID let currentFileId = ''; // 设置当前要删除的文件ID function setCurrentFileId(fileId) { currentFileId = fileId; } // 确认删除:先删GDrive文件,再延迟删数据库记录 async function confirmDelete() { // 执行GDrive删除 await deleteFile(currentFileId); // 保持原有的5秒延迟删除数据库记录 setTimeout(() => { removeFromDb(currentFileId); $('#modal_remove').modal('hide'); }, 5000); } // 保留原有的GDrive和数据库删除函数(这部分功能正常无需修改) async function deleteFile(fileId) { const accessToken = gapi.client.getToken().access_token; const url = 'https://www.googleapis.com/drive/v3/files/' + fileId; return await fetch(url, { method: 'DELETE', headers: { 'Authorization': 'Bearer ' + accessToken } }).then(function (response) { return response.json(); }).then(function (value) { console.log(value); }); } function removeFromDb(fileId) { $.ajax({ type: 'POST', url: 'delete.php', data: { 'fileId': fileId }, success: function(response) { console.log(response); alert("The file has been deleted successfully."); }, error: function(xhr, status, error) { console.error(xhr.responseText); } }); }
关键优化点说明
- 移除了重复id的隐藏按钮,避免了
getElementById()的选择错误问题。 - 通过全局变量
currentFileId关联当前要删除的记录,确保参数传递准确。 - 直接调用删除函数,简化了逻辑,减少了不必要的DOM操作。
内容的提问来源于stack exchange,提问作者Lai Miranda
相关产品推荐
相关产品推荐

