
在使用 bootstrap 5 构建网页表单时,我们常希望在表单成功提交后弹出一个提示信息(例如一个 alert 模态框)。然而,一个常见的困扰是,当用户首次点击发送按钮并看到提示信息后,如果他们点击了提示框的关闭按钮,那么在后续的表单提交中,该提示框将不再显示,除非刷新页面。这极大地影响了用户体验和功能的连贯性。
这个问题的核心在于 Bootstrap 5 Alert 组件的默认行为。当我们为 Alert 的关闭按钮添加 data-bs-dismiss="alert" 属性时,Bootstrap 会在用户点击该按钮后,将整个 Alert 元素从页面的 DOM (Document Object Model) 结构中完全移除,而不仅仅是隐藏它。
考虑以下 HTML 结构:
<div class="alert my-alert alert-warning alert-dismissible fade show d-none" role="alert"> <strong>感谢!</strong> 您的消息已收到。 <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div>
当 JavaScript 代码通过移除 d-none 类来显示此 Alert,然后用户点击 btn-close 按钮时,由于 data-bs-dismiss="alert" 的存在,这个 <div class="alert ..."> 元素会被从 DOM 中删除。一旦元素被删除,后续的 JavaScript 操作(例如再次移除 d-none 类)将无法找到该元素并对其进行操作,因此 Alert 也无法再次显示。
要解决此问题,我们需要改变 Alert 关闭按钮的默认行为,使其在关闭时不再从 DOM 中移除元素,而是仅仅将其隐藏。这可以通过以下两个步骤实现:
移除关闭按钮上的 data-bs-dismiss="alert" 属性,并添加一个自定义的 onclick 事件处理函数来控制 Alert 的隐藏。
原始 HTML (存在问题):
<div class="alert my-alert alert-warning alert-dismissible fade show d-none" role="alert"> <strong>感谢!</strong> 您的消息已收到。 <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div>
修改后的 HTML:
<div class="alert my-alert alert-warning alert-dismissible fade show d-none" role="alert"> <strong>感谢!</strong> 您的消息已收到。 <!-- 移除 data-bs-dismiss 属性,添加自定义 onclick 事件 --> <button type="button" class="btn-close" onclick="hideMyAlert()" aria-label="Close"></button> </div>
这里我们假设自定义的 JavaScript 函数名为 hideMyAlert()。
我们需要在 JavaScript 中实现两个关键功能:
原始 JavaScript (存在问题):
const scriptURL = 'https://script.google.com/macros/......'; // 示例 URL
const form = document.forms['portofolio-contact-form'];
const myAlert = document.querySelector('.alert');
const btnKirim = document.querySelector('.my-btn');
const btnLoading = document.querySelector('.btn-loading');
form.addEventListener('submit', e => {
  e.preventDefault();
  btnLoading.classList.toggle('d-none');
  btnKirim.classList.toggle('d-none');
  fetch(scriptURL, { method: 'POST', body: new FormData(form) })
    .then(response => {
      btnLoading.classList.toggle('d-none');
      btnKirim.classList.toggle('d-none');
      myAlert.classList.toggle('d-none'); // 首次显示有效,但如果元素被移除则失效
      form.reset();
      console.log('Success!', response);
    })
    .catch(error => console.error('Error!', error.message));
});修改后的 JavaScript:
const scriptURL = 'https://script.google.com/macros/s/AKfycbzAovQklbPcjlV0Z0MAgTrvDR--cWl3mhWyfwcOneOcSbRPBnk_cSTCP2LOcUCiG5/exec'; // 替换为你的实际 URL
const form = document.forms['portofolio-contact-form'];
const myAlert = document.querySelector('.alert');
const btnKirim = document.querySelector('.my-btn');
const btnLoading = document.querySelector('.btn-loading');
form.addEventListener('submit', e => {
  e.preventDefault(); // 阻止表单默认提交行为
  btnLoading.classList.toggle('d-none'); // 显示加载按钮
  btnKirim.classList.toggle('d-none');   // 隐藏发送按钮
  fetch(scriptURL, { method: 'POST', body: new FormData(form) })
    .then(response => {
      btnLoading.classList.toggle('d-none'); // 隐藏加载按钮
      btnKirim.classList.toggle('d-none');   // 显示发送按钮
      // 表单提交成功后,移除 'd-none' 类来显示 Alert
      myAlert.classList.remove('d-none'); 
      form.reset(); // 重置表单
      console.log('Success!', response);
    })
    .catch(error => console.error('Error!', error.message));
});
// 定义自定义函数,用于在点击关闭按钮时隐藏 Alert
function hideMyAlert() {
  myAlert.classList.add('d-none'); // 添加 'd-none' 类来隐藏 Alert
}在修改后的 JavaScript 代码中:
结合上述 HTML 和 JavaScript 修改,以下是完整的实现代码:
HTML 文件 (例如 index.html):
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单提交与可重复显示 Alert</title>
    <!-- 引入 Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { padding: 20px; }
        .container { max-width: 600px; margin-top: 50px; }
        .my-alert { margin-bottom: 20px; }
        .d-none { display: none !important; } /* 确保 d-none 有效 */
    </style>
</head>
<body>
    <div class="container">
        <h2>联系我们</h2>
        <!-- 成功提示框,初始隐藏 -->
        <div class="alert my-alert alert-warning alert-dismissible fade show d-none" role="alert">
            <strong>感谢!</strong> 您的消息已收到。
            <!-- 移除 data-bs-dismiss,添加自定义 onclick -->
            <button type="button" class="btn-close" onclick="hideMyAlert()" aria-label="Close"></button>
        </div>
        <form name="portofolio-contact-form">
            <div class="mb-3">
                <label for="name" class="form-label">姓名</label>
                <input type="text" class="form-control" id="name" name="name" required>
            </div>
            <div class="mb-3">
                <label for="email" class="form-label">邮箱</label>
                <input type="email" class="form-control" id="email" name="email" required>
            </div>
            <div class="mb-3">
                <label for="message" class="form-label">消息</label>
                <textarea class="form-control" id="message" name="message" rows="3" required></textarea>
            </div>
            <button type="submit" class="btn btn-primary my-btn">发送</button>
            <button class="btn btn-primary btn-loading d-none" type="button" disabled>
                <span class="spinner-border spinner-border-sm" aria-hidden="true"></span>
                <span role="status">加载中...</span>
            </button>
        </form>
    </div>
    <!-- 引入 Bootstrap 5 JS (如果需要其他 Bootstrap 组件,例如 Modal、Dropdown等) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const scriptURL = 'https://script.google.com/macros/s/AKfycbzAovQklbPcjlV0Z0MAgTrvDR--cWl3mhWyfwcOneOcSbRPBnk_cSTCP2LOcUCiG5/exec'; // 替换为你的 Google Apps Script URL
        const form = document.forms['portofolio-contact-form'];
        const myAlert = document.querySelector('.my-alert'); // 使用更具体的类名选择器
        const btnKirim = document.querySelector('.my-btn');
        const btnLoading = document.querySelector('.btn-loading');
        form.addEventListener('submit', e => {
            e.preventDefault(); 
            btnLoading.classList.toggle('d-none');
            btnKirim.classList.toggle('d-none');
            fetch(scriptURL, { method: 'POST', body: new FormData(form) })
                .then(response => {
                    btnLoading.classList.toggle('d-none');
                    btnKirim.classList.toggle('d-none');
                    myAlert.classList.remove('d-none'); // 显示 Alert
                    form.reset(); 
                    console.log('Success!', response);
                })
                .catch(error => {
                    console.error('Error!', error.message);
                    // 错误处理,例如显示一个错误提示
                    btnLoading.classList.toggle('d-none');
                    btnKirim.classList.toggle('d-none');
                });
        });
        // 自定义函数,用于隐藏 Alert
        function hideMyAlert() {
            myAlert.classList.add('d-none'); // 隐藏 Alert
        }
    </script>
</body>
</html>通过以上方法,我们成功地解决了 Bootstrap Alert 模态框在首次关闭后无法再次显示的问题,实现了其可重复使用的功能,从而提升了用户界面的交互性和鲁棒性。
以上就是解决 Bootstrap Alert 模态框重复显示失效问题的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号