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

如何在Bootstrap 5中通过下拉选择框change事件触发Popover?

实现下拉选择框change事件触发Bootstrap 5 Popover

核心实现逻辑

监听下拉选择框的change事件,根据选中的选项值匹配对应的Popover元素,先关闭所有已打开的Popover,再触发目标Popover的显示(同时让触发元素获得焦点,适配focus触发类型)。

完整代码示例

HTML 代码

<select id="locationSelect" class="form-select">
  <option selected disabled>All Locations</option>
  <option value="01">001</option>
  <option value="02">002</option>
  <option value="03">003</option>
  <option value="04">004</option>
</select>

<div class="about-location-list">
  <a tabindex="0" class="about-location-list-item" role="button" data-bs-toggle="popover" data-bs-html="true" data-bs-placement="right" data-bs-trigger="focus" data-bs-custom-class="custom-popover" data-bs-title="Title 01" data-bs-content='<span>Lorim ipsum 01</span>'>Title 01</a>
  <a tabindex="1" class="about-location-list-item" role="button" data-bs-toggle="popover" data-bs-html="true" data-bs-placement="right" data-bs-trigger="focus" data-bs-custom-class="custom-popover" data-bs-title="Title 02" data-bs-content='<span>Lorim ipsum 02</span>'>Title 02</a>
  <a tabindex="2" class="about-location-list-item" role="button" data-bs-toggle="popover" data-bs-html="true" data-bs-placement="right" data-bs-trigger="focus" data-bs-custom-class="custom-popover" data-bs-title="Title 03" data-bs-content='<span>Lorim ipsum 03</span>'>Title 03</a>
  <a tabindex="3" class="about-location-list-item" role="button" data-bs-toggle="popover" data-bs-html="true" data-bs-placement="right" data-bs-trigger="focus" data-bs-custom-class="custom-popover" data-bs-title="Title 04" data-bs-content='<span>Lorim ipsum 04</span>'>Title 04</a>
</div>

JavaScript 代码

// 初始化所有Popover
const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]')
const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl))

// 获取下拉选择框元素
const locationSelect = document.getElementById('locationSelect')

// 监听change事件
locationSelect.addEventListener('change', function() {
  const selectedValue = this.value
  if (!selectedValue) return

  // 计算对应Popover的索引:value"01"对应索引0,"02"对应索引1,以此类推
  const popoverIndex = parseInt(selectedValue) - 1

  // 先关闭所有已打开的Popover
  popoverList.forEach(popover => popover.hide())

  // 获取目标Popover实例和对应的触发元素
  const targetPopover = popoverList[popoverIndex]
  const targetTrigger = popoverTriggerList[popoverIndex]

  // 让触发元素获得焦点并显示Popover
  targetTrigger.focus()
  targetPopover.show()
})

关键说明

  • 给下拉选择框添加了id用于快速获取元素,方便事件绑定
  • 通过选中值计算对应Popover的索引,建立选项与Popover的对应关系
  • 每次触发前关闭所有Popover,避免多个Popover同时显示
  • 因为Popover的触发类型是focus,所以需要手动让触发元素获得焦点,确保Popover正常显示且不会立即关闭

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:01:16