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

如何将含引号的HTML元素放入Bootstrap弹出框?

解决Bootstrap Popover嵌套带Razor链接的引号冲突问题

别死磕在data-content属性里硬塞HTML了,直接用下面两种靠谱方法搞定:

方法一:用隐藏元素存内容,JS关联Popover

把要显示的HTML单独放在隐藏容器里,彻底避开属性里的引号冲突,还方便后续修改内容:

  1. 调整按钮代码,去掉data-content,加个唯一ID:
<button type="button" class="btn btn-secondary" id="editPopoverBtn" data-container="body" data-bs-toggle="popover" data-placement="left">
   Popover Text
</button>
  1. 写一个隐藏的div,放入你的编辑链接:
<div id="popoverEditContent" style="display: none;">
    <a href="@Url.Action("Edit", "RentalHistories", new { id = item.RentalHistoryId })">
        EDIT
    </a>
</div>
  1. 初始化Popover时,指定内容为隐藏元素的HTML,同时必须开启html: true(否则HTML会被当成纯文本渲染):
document.addEventListener('DOMContentLoaded', function() {
    const popoverBtn = document.getElementById('editPopoverBtn');
    const contentHtml = document.getElementById('popoverEditContent').innerHTML;
    new bootstrap.Popover(popoverBtn, {
        content: contentHtml,
        html: true
    });
});

方法二:JS直接生成Popover内容

如果不想加额外的隐藏元素,直接在JS里拼接内容更简洁:

  1. 按钮代码(同样去掉data-content):
<button type="button" class="btn btn-secondary" id="editPopoverBtn" data-container="body" data-bs-toggle="popover" data-placement="left">
   Popover Text
</button>
  1. JS里先通过Razor生成编辑URL,再拼接成需要的HTML内容:
document.addEventListener('DOMContentLoaded', function() {
    // 先让Razor生成正确的编辑URL
    const editUrl = '@Url.Action("Edit", "RentalHistories", new { id = item.RentalHistoryId })';
    // 拼接成目标HTML
    const popoverContent = `<a href="${editUrl}">EDIT</a>`;
    
    new bootstrap.Popover(document.getElementById('editPopoverBtn'), {
        content: popoverContent,
        html: true
    });
});

为啥之前的方法不行?

你尝试的单引号、转义双引号失效,核心原因有两个:一是Razor引擎会先解析@Url.Action生成带双引号的URL,和外层data-content的引号嵌套冲突;二是Bootstrap默认会把data-content的内容当纯文本渲染,必须开启html: true才能解析HTML标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:24:28