twitter-bootstrap 加载 Ajax 时 Bootstrap Popover 不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22277300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 20:15:07  来源:igfitidea点击:

Bootstrap Popover Not Working When Loaded With Ajax

javascriptjqueryhtmlajaxtwitter-bootstrap

提问by user3377041

When I load Bootstrap popver content with ajax, the popover is not showing.

当我用 ajax 加载 Bootstrap popver 内容时,popover 没有显示。

Javascript:

Javascript:

var id = 1;
$.post("load.php?pageid",
        {
          pageid:id;
        },
        function(data,status){
         document.getElementById("body").innerHTML=data;
        });

HTML response:

HTML 响应:

<a href="#" id="example" class="btn btn-danger" rel="popover" data-content="It's so simple to create a tooltop for my website!" data-original-title="Twitter Bootstrap Popover">hover for popover</a>
<script>  
$(function ()  
{ $("#example").popover();  
});  
</script> 

When I place the HTML response above directly in the <body id="body"></body>code, the popover works fine. I dont understand what is going wrong here.

当我将上面的 HTML 响应直接放在<body id="body"></body>代码中时,弹出框工作正常。我不明白这里出了什么问题。

回答by Jason Reid

The problem is that you're setting up the popover inside of the function $(). Rather than

问题是您正在函数 $() 内设置弹出窗口。而不是

$(function ()  
{ $("#example").popover();  
}); 

It should be just

应该只是

$("#example").popover();  

Or perhaps better

或者也许更好

$(document).ajaxComplete(function() {
  $("#example").popover();
});

The reason being that any function inside of $() is run when the document is first finished loading, when the "document ready" event is fired. When that code is pasted inside of the original HTML, it works because it's present when the document finishes loading.

原因是 $() 中的任何函数在文档第一次完成加载时运行,当“文档就绪”事件被触发时。当该代码粘贴到原始 HTML 中时,它会起作用,因为它在文档完成加载时出现。

When it's the response from an AJAX call, it won't run inside of $(), because the "document ready" event already fired some time ago.

当它是来自 AJAX 调用的响应时,它不会在 $() 内运行,因为“文档就绪”事件已经在一段时间前触发了。

回答by batoutofhell

<script>$(function () {  $('[data-toggle="tooltip"]').tooltip()});</script>

Add this at the end of whatever you are loading in with ajax. You should already have this somewhere to opt-in to the tooltip, but put it again to re-initialize the tooltip.

在您使用 ajax 加载的任何内容的末尾添加它。您应该已经在某处选择加入工具提示,但再次放置它以重新初始化工具提示。

回答by Rahma Samaroon

with the help of jQuery you can initialize all things that needs to be initialized using

在 jQuery 的帮助下,您可以初始化所有需要使用的东西

$(document).ajaxSuccess(function () {
    $("[data-toggle=popover]").popover();
    $("[data-toggle=tooltip]").tooltip();
    // any other code
});

inspired from Olaf Dietscheanswer

灵感来自Olaf Dietsche 的回答