简体   繁体   中英

How to get html into a bootstrap 2.3.2 popover, dynamically

I have a button where I would like to create a bootstrap popover containing html dynamically when I hover over it. So far I have:

$(".btn.btn-navbar").hover(function() {
  html = '<ul class="nav"><li><a href="#">hola</li><li><a href="#">hola2</li></ul>';
  $link = $('<a href="myreference.html" class="p1" data-html="true" data-bind="popover"' 
          + ' data-content="' + html + '">');

  console.log('$link', $link);
  $(this).html($link);

  // Trigger the popover to open
  $link = $(this).find('a');
  $link.popover("show");
}, function() {
  console.log('$hi there ');
});

jsfiddle

I'm having trouble getting the html into the popover properly.
Can someone give me a hand with this.

Not sure if you need to create a link dynamically with popover or you need to create popover with html inside only. I have a jsFiddle showing how to create popover dynamically with custom html inside.

function createHoverPopover(htmlContent, jqueryElement, direction) {
jqueryElement.popover({
    html: true,
    placement: direction,
    trigger: "hover",
    content: htmlContent,
    selector: true
}); }

Your actual problem here is ' data-content="' + html + '">'

You should do the concatenating your self to see what is happening.
The result of it would be:

<a href="myreference.html" class="p1" data-html="true" data-bind="popover" data-content="<ul class="nav"><li><a href="#">hola</li><li><a href="#">hola2</li></ul>">

The problem is at this part:

data-content="<ul class="nav"><li>

The data-content attribute will only contain <ul class= , additionally your <a> tag will end here data-content="<ul class="nav">

To correctly add the html to the data-content you should do it this way:

html = '<ul class="nav"><li><a href="#">hola</li><li><a href="#">hola2</li></ul>';
$link = $('<a href="myreference.html" class="p1" data-html="true" data-bind="popover">');
$link.data('content', html);

Your problem is the string concatenation, I would create the html element like

html = '<ul class="nav"><li><a href="#">hola</li><li><a href="#">hola2</li></ul>';
$link = $('<a />', {
    href: 'myreference.html',
    "data-html": 'true',
    "data-bind": 'popover',
    "data-content": html
});

Demo: Fiddle

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