将 Bootstrap 弹出窗口添加到特定的 div 元素

Add Bootstrap popover to a specific div element

我正在尝试将 bootstrap 弹出窗口添加到包含任意内容的 div 元素(但我想出的方法不起作用):

<div id="popover-target">
   <h3>I need a popover</h3>
      <p>
        This is some content for the section
        that needs to be explained by the popover.
      </p>
</div>
<button class="btn">Show popover</button>

<script>
    $(function(){
        $('.btn').click(function(){
            $('#popover-target').popover({title: 'Title', content: 'Test Content', container: 'body', placement: 'right'});
        });
    });
</script>

如果我将 $('#popover-target') 更改为 $('.btn'),则弹出窗口会正确显示。有什么想法吗?

您刚刚初始化了单击按钮时的弹出窗口,如果您在单击按钮后将鼠标悬停在 #popover-target div 上,应该可以正常工作。如果你想在鼠标悬停在按钮点击后显示它,你可以使用 .popover('show') 比如:

$('.btn').click(function() {
  $('#popover-target').popover({
      trigger: 'hover',
      title: 'Title',
      content: 'Test Content',
      placement: 'bottom'
    })
    .popover('show');
});

$(function(){
$('.btn').popover({
      container: "body",
      html: true,
      content: function () {
        return '<div class="popover-message">Hello</div>';
      }
    });
    
  
});

$('.btn').click(function(){
      $('#btn').popover();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>


<div id="popover-target">
   <h3>I need a popover</h3>
      <p>
        This is some content for the section
        that needs to be explained by the popover.
      </p>
</div>
<button class="btn">Show popover</button>