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

不使用jQuery编写Bootstrap 5兼容JS代码的方法及现有代码适配问题

问题解答

1. 现有jQuery代码能否直接在无jQuery的Bootstrap 5环境运行

答案是不能,原因如下:

  • Bootstrap 5 已完全移除对jQuery的依赖,默认运行环境不会加载jQuery库
  • 你提供的代码中所有$、jQuery开头的调用都是jQuery专属API,没有jQuery库支持的情况下浏览器无法识别这些语法,运行会直接抛出未定义错误。

2. 原生JavaScript实现同等功能的代码

2.1 直接修改样式版本

document.addEventListener('DOMContentLoaded', function() {
  setInterval(function() {
    const pillsProfile = document.querySelector('#pills-profile');
    const id1 = document.querySelector('#id1');
    const id2 = document.querySelector('#id2');
    // 可选链+空值合并避免元素不存在时报错,兼容性要求高可自行补充元素存在判断
    const attend = pillsProfile?.classList.contains('active') ?? false;
    if (attend) {
      id2.style.display = 'block';
      id1.style.display = 'none';
    } else {
      id2.style.display = 'none';
      id1.style.display = 'block';
    }
  }, 1000);
});

2.2 更符合Bootstrap 5规范的类切换版本(推荐)

利用Bootstrap内置的d-none工具类实现显隐,避免直接操作样式,和Bootstrap设计规范保持一致:

document.addEventListener('DOMContentLoaded', function() {
  setInterval(function() {
    const pillsProfile = document.querySelector('#pills-profile');
    const id1 = document.querySelector('#id1');
    const id2 = document.querySelector('#id2');
    const attend = pillsProfile?.classList.contains('active') ?? false;
    // classList.toggle第二个参数为布尔值,true则添加类,false则移除类
    id2.classList.toggle('d-none', !attend);
    id1.classList.toggle('d-none', attend);
  }, 1000);
});

3. 核心语法替换说明

  • 用原生DOMContentLoaded事件替代jQuery的$(document).ready,确保DOM加载完成后再执行代码
  • 用document.querySelector替代jQuery的ID选择器
  • 用元素的classList.contains方法替代jQuery的hasClass方法判断类名是否存在
  • 用classList.toggle操作Bootstrap内置工具类实现显隐,后续调整样式不需要修改JS逻辑,维护成本更低

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:27:04