模态框关闭时表单重置JS代码单页有效另一页失效问题排查
Hey there! Let's figure out why your #addProjectModal isn't clearing the form when it closes, even though the exact same logic works flawlessly for #addadminprofile.
核心原因:HTML结构损坏
Looking at the HTML snippet you shared, the #addProjectModal has unclosed nested elements—that's the root of your problem! Let me highlight the issue:
<!-- Modal --> <div class="modal fade" id="addProjectModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-xl" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ajouter un projet</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <form action="suiviProjet.php" method="POST"> <!-- 这里直接开始了另一个模态框,完全没闭合form、modal-content、modal-dialog、modal的div标签! -->
When HTML tags aren't properly closed, browsers can't parse the DOM structure correctly. This means jQuery can't reliably find the #addProjectModal element or its nested form, so your event listener never gets triggered.
修复方案:补全闭合标签
You need to close all unclosed elements for #addProjectModal before starting the next modal. Here's the corrected, complete HTML for #addProjectModal:
<!-- Modal --> <div class="modal fade" id="addProjectModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-xl" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ajouter un projet</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <form action="suiviProjet.php" method="POST"> <!-- 在这里放置你的表单输入字段 --> </form> <!-- 闭合form标签 --> <div class="modal-footer"> <!-- 如果有底部按钮,放在这里 --> <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button> <button type="submit" class="btn btn-primary">Enregistrer</button> </div> </div> <!-- 闭合modal-content标签 --> </div> <!-- 闭合modal-dialog标签 --> </div> <!-- 闭合modal标签 -->
额外优化建议
- Wrap your JavaScript code in a
$(document).ready()block to ensure it runs only after the DOM is fully loaded:$(document).ready(function() { $('#addProjectModal').on('hidden.bs.modal', function () { $('#addProjectModal form')[0].reset(); }); $('#addadminprofile').on('hidden.bs.modal', function () { $('#addadminprofile form')[0].reset(); }); }); - Double-check that there are no duplicate
idvalues on the page—each modal must have a unique identifier.
Once you fix the broken HTML structure, your existing JavaScript will work perfectly for both modals!
内容的提问来源于stack exchange,提问作者Simon Stifler

