简体   繁体   中英

bootstrap 3 popover on dynamically generated content doesnt work

I am trying to enable bootstrap 3 popovers on dynamically generated content. Ive looked into other posts as to how they have gotten theirs to work, but im struggling to understand why this wont work

$(document).on('click','[data-toggle="popover"]', function(){
$(this).popover({
    content: _popovercontent,
    title:'Assignee',
    html:true
   });
});

I cant seem to see any errors within Firebug, but is there any reason why I cant attach this to the event when being called on ?

Problem

.popover() only initializes the popover. This means that what your code currently does is set up the popup when the click event is triggered (I'm guessing it would show on the second click because it would have been set up by the first one - the next problem is that now you're trying to set it up again on the second click).

Solution

If the content is dynamically generated, you should rather initialize the popover on it directly when it is inserted into the DOM. Something like:

// The dynamically generated content
var $dynamicContent = $('<div><span data-toggle="popover"></span></div>');

// When you insert into the DOM, filter for you popover and initialize
$dynamicContent.appendTo('body').filter('[data-toggle="popover"]').popover({
  content: _popovercontent,
  title:'Assignee',
  html:true
});

For the first click, you need to manually show the popover

 var _popovercontent = 'this is popover'; $(document).on('click', '[data-toggle="popover"]', function() { var $this = $(this); //if not already initialized if (!$this.data('bs.popover')) { $this.popover({ content: _popovercontent, title: 'Assignee', html: true }).popover('show'); } }); $('button').click(function () { $('#ct').append('<a href="#" data-toggle="popover">Some content</a>') }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css" /> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap-theme.css" /> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.js"></script> <button>Add</button> <div id="ct"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM