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

如何在Bootstrap 5 Popover中正确获取并插入按钮的data-attribute属性值

解决Bootstrap 5 Popover中无法获取按钮data属性的问题

你的问题核心是初始化popover时的上下文错误,导致$(this)没指向你期望的单个按钮元素。直接上修正后的可运行代码:

$('[data-bs-toggle="popover"]').popover({ 
  html: true, 
  container: 'body', 
  placement: 'top', 
  content: function() {
    // 此时this就是当前触发popover的按钮元素
    const username = $(this).data('username');
    return `<a href='teachers.asp?action=delete&user=${username}'>Click Here</a> to permanently delete this teacher.`;
  }
});

为什么原来的代码会返回undefined?

你之前把content设为静态字符串,在批量初始化popover的阶段,$(this)指向的是整个$('[data-bs-toggle="popover"]')的jQuery集合,而非单个触发popover的按钮。这时候去读取data-username自然拿不到对应按钮的属性值,只能返回undefined。

改成函数形式后,Bootstrap会在每次popover触发(比如鼠标悬停)时执行这个函数,此时函数内部的this会精准指向当前触发的按钮元素,这样就能正确获取到该按钮的data-username值了。

另外小建议:用ES6模板字符串(反引号包裹)拼接HTML内容,比传统的加号拼接可读性更高,也不容易出现语法疏漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:12:38