Bootstrap 弹出窗口中调用了两次内容函数

Content function called twice in Bootstrap Popover

我有一个 Bootstrap 弹出框,它加载了一个函数,如下所示:

var index = 0;

$('#Button').popover({
    html:true,
    placement:'right',
    content:function(){
      index = index +1;
      return index;
    }
});

而 HTML 只是:

<input id="Button" value='popover' type='button'/>

所以,当我点击按钮时,我应该得到 1、2、3 等等...

但是,我得到 2,4,6... 因为它调用了 "content" 函数两次。这是为什么?这是一个错误还是我做错了什么?

Here is the fiddle.

此问题不在您的代码中,而是来自 bootstrap 本身。 看这个 link: https://github.com/twbs/bootstrap/issues/12563

因此,您可以自行修复它。设置一些标志以检查是否显示弹出窗口。

遇到了这个问题并使用 flag 解决了它。如前所述,这是 Bootstrap 代码中的错误。仅供参考,第一个电话是检查是否进行第二个电话。第二次调用是在实际渲染发生时。

所以逻辑上应该是跳过第一次调用,允许第二次调用。 (而不是导致不呈现任何内容的其他方式)。出于某种原因,第一次调用不应该 return null。然后不进行第二个调用。有了这些,您可以查看下面的代码以获取更多参考。

function popoverHandler(element) {
   
    contentCalled = false; // flag for checking 
    
    element.popover({
        animation: true, 
        container:"body",
        placement: "bottom",
        trigger:"hover",
        "html": true,
        "content": function(){
            var div_id =  "tmp-id-" + $.now();
            return fetchResults(div_id);
        }
    });

    function fetchResults(div_id){
    
        if (!contentCalled) {
            contentCalled = true;
            return " ";
        }
        else {
            $.ajax({
                url         : "getResults",
                type        : "POST",
                data        : <your data>,
                contentType : 'application/json; charset=UTF-8',
                dataType    : 'json',
                success     : function(response){
                                contentCalled = false;
                                // form htmlOutput
                                $('#'+div_id).html(htmlOutput);
                            }
            });
            return '<div id="'+ div_id +'"><img src="assets/img/loading.gif"/> </div>';
        }
    }
}