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

如何在用户关闭Bootstrap警告框时设置cookie且不修改原有代码?

实现方案

有,无需修改你现有的HTML代码,直接通过监听Bootstrap警告框组件的原生事件即可实现需求,不需要额外给关闭按钮绑定onclick事件。

实现原理

Bootstrap官方为Alert组件内置了专属事件:

  • closed.bs.alert:警告框关闭动画完全执行完成后触发,可直接全局监听该事件拿到被关闭的警告框元素,执行存cookie的逻辑。

代码示例(Bootstrap 5 原生JS版本,无需引入jQuery)

监听关闭事件存cookie

// 全局监听所有警告框的关闭完成事件
document.addEventListener('closed.bs.alert', function (event) {
  // event.target 为被关闭的警告框DOM元素
  // 可根据警告框的id、类名等属性区分不同的警告框,无id则使用通用标识
  const alertKey = event.target.id || 'global_warning_alert';
  // 存储cookie,示例有效期为1天,可自行调整max-age(单位:秒)
  document.cookie = `alert_${alertKey}_closed=1; max-age=86400; path=/`;
});

页面加载时自动隐藏已关闭过的警告框(可选附加功能)

document.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('.alert-dismissible').forEach(function (alertEl) {
    const alertKey = alertEl.id || 'global_warning_alert';
    if (document.cookie.includes(`alert_${alertKey}_closed=1`)) {
      // 调用Bootstrap Alert官方方法关闭已确认过的警告框
      bootstrap.Alert.getOrCreateInstance(alertEl).close();
    }
  });
});

代码示例(Bootstrap 3/4 jQuery版本)

// 监听关闭事件存cookie
$(document).on('closed.bs.alert', '.alert', function () {
  const alertKey = $(this).attr('id') || 'global_warning_alert';
  document.cookie = `alert_${alertKey}_closed=1; max-age=86400; path=/`;
});

// 页面加载自动隐藏已关闭的警告框
$(function () {
  $('.alert-dismissible').each(function () {
    const alertKey = $(this).attr('id') || 'global_warning_alert';
    if (document.cookie.includes(`alert_${alertKey}_closed=1`)) {
      $(this).alert('close');
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:06:04