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

Fetch仅首次生效:动态切换合作伙伴状态后页面异常灰化

解决Bootstrap模态框状态变更后页面灰化问题

问题根源

核心问题有两个:

  • 重复绑定点击事件:每次切换开关时,都会给模态框确认按钮新增一次点击监听,多次绑定后逻辑混乱,导致模态框状态异常。
  • 未正确关闭模态框:状态变更完成后,没有调用Bootstrap模态框的官方关闭方法,导致模态框的灰层(backdrop)未被移除,出现页面灰化但模态框不可见的现象。

修复方案及代码

以下是优化后的代码,适配Bootstrap 5(若使用Bootstrap 4,可调整模态框调用方式):

// Activation ou désactivation dynamique d'un partenaire
let currentStatutUrl = '';
const Modal = document.getElementById('exampleModal');
const confirmBtn = Modal.querySelector('.modal-footer button:last-child');

// 仅绑定一次确认按钮的点击事件
confirmBtn.addEventListener("click", () => {
    if (!currentStatutUrl) return;

    fetch(currentStatutUrl)
    .then((response) => {
        if (!response.ok) throw new Error('Erreur réseau');
        return response.json()
    }).then(data => {
        console.log(data);
        const content = document.querySelector('#formCheck');
        content.innerHTML = data.content;
        // 调用Bootstrap API关闭模态框,移除灰层
        const bootstrapModal = bootstrap.Modal.getInstance(Modal);
        bootstrapModal.hide();
    }).catch((err) => {
        console.log('Erreur : '+ err);
        // 出错时也关闭模态框,避免页面卡住
        const bootstrapModal = bootstrap.Modal.getInstance(Modal);
        bootstrapModal.hide();
    });     
});

// 绑定开关的状态变更事件
document.querySelectorAll(".form-switch-statut-partenaire input").forEach(input => {
    input.addEventListener("change", () => {
        // 存储当前开关对应的请求URL
        currentStatutUrl = input.dataset.path;
        // 打开模态框
        const bootstrapModal = new bootstrap.Modal(Modal);
        bootstrapModal.show();
    });
});

// 模态框关闭后重置URL,避免残留旧值
Modal.addEventListener('hidden.bs.modal', () => {
    currentStatutUrl = '';
});

关键修改点

  1. 将确认按钮的点击事件移到循环外部,仅绑定一次,避免重复执行逻辑。
  2. 使用变量currentStatutUrl存储当前开关对应的请求地址,确保点击确认时使用最新的URL。
  3. 请求完成(成功/失败)后,调用Bootstrap模态框的hide()方法,彻底关闭模态框并移除灰层。
  4. 添加模态框关闭事件监听,重置存储的URL,避免下次打开模态框时使用旧地址。

内容的提问来源于stack exchange,提问作者Marine bde

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:40:39