Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

javascript - Twitter Bootstrap Popovers not working for Dynamically Generated Content

New to posting on stackoverflow here, so my apologies in advance if I messed anything up here.

I'm using Twitter Bootstrap's popovers. My popovers seem to be working for elements that I manually type into my HTML document - but NOT the elements that I dynamically generate via Javascript / Ajax.

For example, the popover seems to work if I manually add this directly to my HTML document:

<p rel=popover data-content='It is so simple to create a tooltop for my website!' data-original-title='Twitter Bootstrap Popover'>hover for popover</p>

But what I really need is for my dynamically generated elements to have popovers. I use an XMLHttpRequest to send a request to a PHP file, and then grab the responseText and display it. When I add this line of code to my aforementioned PHP file:

 echo "<p rel=popover data-content='It is so simple to create a tooltop for my website!' data-original-title='Twitter Bootstrap Popover'>hover for popover</p>";

... surely enough, the words "hover for popover" appear - but the popover itself doesn't work!

This has been driving me nuts for some time and it would be incredible if someone could lend me a helping hand! I've also added the JQuery function I'm using to enable Bootstrap's popovers below, for what that's worth.

$(function (){
$("[rel=popover]").popover({placement:'left'});
}); 

I've done a thorough search of similar problems and the best I could find was this link. But that link doesn't seem to have any solutions either. Thanks in advance again!

UPDATE:

Fixed! Many thanks to everyone who helped out. My problem was that the function was being called BEFORE the elements were added into the Document Object Model. There are multiple possible fixes - I simply tested out the solution by shifting the popover function to the END of the Ajax function and it worked!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to call $("[rel=popover]").popover({placement:'left'}); AFTER the elements are in the DOM.

UPDATE

If you are using jQuery

$(element_selector)
  // load results into HTML of element_selector
  .load('your/php/file')
  // when done, initialize popovers
  .done(function(){
    $("[rel=popover]").popover({placement:'left'});
  });

OR a catch all for jQuery ajax requests

$.ajaxComplete(function(){
    $("[rel=popover]").popover({placement:'left'});
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...