admin管理员组

文章数量:1187337

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

Javascript:

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

HTML response:

<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.

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

Javascript:

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

HTML response:

<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.

Share Improve this question asked Mar 9, 2014 at 1:27 user3377041user3377041 1031 gold badge1 silver badge4 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 16

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.

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.

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

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

inspired from Olaf Dietsche answer

<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.

本文标签: javascriptBootstrap Popover Not Working When Loaded With AjaxStack Overflow