简体   繁体   中英

Dynamically added bootstrap popover not working

I have found some similar questions, but still could get it to work. So I know that if you add some html content on button click, that jQuery is not listening to it. But I don't know how to fix that in my case. Hope someone can help. If you click on the first "my popover" it's working. Also on the red button. But if you add a new "my popover" with the "click me" button, then the new "my popover" is not working.

Edit: And every popover has it's own unique content that is dynamically created. So I can't have one content for all.

Here the fiddle jsfiddle

Here my "button"

<span class="mypopover" data-html="true" data-toggle="popover" title="Title" data-content="Content">
  my popover
</span>

Here my popover js click function

$(".mypopover").popover({
  trigger: "click",
  sanitize: false,
  html: true,
  animation: true,
  container: "#mycontainer",
});

$(document).on("click", ".mypopover", function (event) {
  event.stopPropagation();
});

$(document).on("click", function () {
  $(".mypopover").popover("hide");
});

When you call $(".mypopover").popover(...) you add popover to all existing elements with class mypopover . In order for popover to work on dynamically added elements, you must execute the same code again. But fortunately there's better solution:

You can initialize popover on the body and make use of selector property of popover constructor in the following way:

$("body").popover({
        trigger: "click",
        sanitize: false,
        html: true,
        animation: true,
        selector: '.mypopover',
        container: '#mycontainer',
    });

Here 's the 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