如何更改已显示的引导程序弹出窗口的内容

How to change content of a bootstrap popover that has already been displayed?

本文关键字:窗口 引导程序 何更改 显示      更新时间:2023-09-26

我有一个表单,其中输入了两次密码。我检查密码的复杂性和一致性,并在INPUT字段的弹出窗口中显示适当的错误消息:

<a href="#" id="aIdPwd2" data-toggle="manual" data-content="The password entered does not match the one previously entered" data-placement="right" href="#" rel="popover">
<input type="password" id="iIdPwd2" class="fmt1" size="60" value=""/>
</a>

使用此代码:

$("#aIdPwd2").popover({content: msg});

您可以选择动态显示消息。但一旦它被显示了一次,它就会一直保持不变。

我读了很多关于这个流行问题的文章,并尝试了很多方法(将两个不同的popover附加到同一输入,更改getElementsByClassName中的内部html("popover内容"),销毁并重新创建popover,..),但迄今为止没有取得任何成功。

关于如何更改已显示的引导程序popover的内容或任何类型的解决方案将不胜感激。

在Twitter Bootstrap 3中,我只更新内容,然后调用show。调用show可确保其正确调整大小,然后正确定位。

$(".notes").data("bs.popover").options.content="Content1";
$(".notes").popover("show");
$(".notes").data("bs.popover").options.content="Content2";
$(".notes").popover("show");

如果您使用数据标记来显示内容,则需要更新数据标记,因为它优先。例如

$(".notes").attr("data-content","Content1");
$(".notes").popover("show");
$(".notes").attr("data-content","Content2");
$(".notes").popover("show");

我更喜欢第二种选择,因为它没有;t通过执行data(bs.popover)访问内部,但第一个选项要快得多,因为它不更新dom。所以,选择让你的船漂浮的东西。

document.getElementsByClassName("popover-content")[0].innerHTML = 'something else';

确定这不管用吗?

在这个页面上试用了一下,结果不出所料。

更新:只有当popover可见时,它才会工作,因为每个mouseover/mouseout事件都会重新创建/销毁元素

我想这不是最好的解决方案,但你可以这样做:

var msg = 'ben123 is not a goddamn password!';
document.getElementById('password').addEventListener('mouseover', function() {  
    document.getElementsByClassName("popover-content")[0].innerHTML = msg; 
});

并在需要时更改msg

依赖popover('show')的解决方案的问题是,如果在show事件的事件处理程序中执行此操作,则最终会出现无限循环。

如果你只想在弹出窗口中显示一些已经显示的内容,你需要直接修改DOM:

$("#aIdPwd2").next(".popover").find(".popover-content").html(msg);

例如,如果您想要一个从API加载一些数据并在悬停时显示在弹出窗口内容中的弹出窗口:

DOM:

<a href="#" id="myPopover" data-toggle="popover" data-title="Details" data-api-parameter="someValue">Hover here for details</a>

jQuery:

$("#myPopover").popover({
    trigger: 'hover'
}).on('shown.bs.popover', function () {
    var popover = $(this);
    var contentEl = popover.next(".popover").find(".popover-content");
    // Show spinner while waiting for data to be fetched
    contentEl.html("<i class='fa fa-spinner fa-pulse fa-2x fa-fw'></i>");
    var myParameter = popover.data('api-parameter');
    $.getJSON("http://api.example.com", {
        'apiParameter': myParameter
    }).done(function (data) {
        var result = data['apiReturnValue'];
        contentEl.html(result);
    }).fail(function (data) {
        result = "No info found.";
        contentEl.html(result);
    });
});

当然,这是假设你信任api.example.com提供的数据。如果不信任,你可能会想逃离返回的数据,以减轻XSS攻击。

要替换元素上popover的内容,请首先调用destroy。在Bootstrap 3.1.1 上测试

$("#aIdPwd2").popover('destroy').popover({content: msg});