programing

부트스트랩 팝업에 닫기 버튼 삽입하는 방법

stoneblock 2023. 9. 26. 21:57

부트스트랩 팝업에 닫기 버튼 삽입하는 방법

JS:

$(function(){
  $("#example").popover({
    placement: 'bottom',
    html: 'true',
    title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>',
    content : 'test'
  })
  $('html').click(function() {
    $('#close').popover('hide');
  });
});

HTML:

<button type="button" id="example" class="btn btn-primary" ></button>

당신의 코드가 당신의 팝업을 보여주지 않는다고 적습니다.

이 문제를 발견한 사람?

마크업을 제대로 해야 합니다.

<button type="button" id="example" class="btn btn-primary">example</button>

그런 다음, 요소 자체 내부에 클로즈 핸들러를 부착하는 것이 한 가지 방법이며, 다음과 같은 작업이 수행됩니다.

$(document).ready(function() {
    $("#example").popover({
        placement: 'bottom',
        html: 'true',
        title : '<span class="text-info"><strong>title</strong></span>'+
                '<button type="button" id="close" class="close" onclick="$(&quot;#example&quot;).popover(&quot;hide&quot;);">&times;</button>',
        content : 'test'
    });
});  

저는 여러 팝오버와 부트스트랩 3에 적합한 무언가를 찾아야 했습니다.

제가 한 일은 이렇습니다.

저는 팝업 작업을 하고 싶은 요소가 여러 개 있어서 ids를 사용하고 싶지 않았습니다.

마크업은 다음과 같습니다.

<button class="btn btn-link foo" type="button">Show Popover 1</button>
<button class="btn btn-link foo" type="button">Show Popover 2</button>
<button class="btn btn-link foo" type="button">Show Popover 3</button>

팝업 내부의 저장 및 닫기 버튼의 내용:

var contentHtml = [
    '<div>',
        '<button class="btn btn-link cancel">Cancel</button>',
        '<button class="btn btn-primary save">Save</button>',
    '</div>'].join('\n');

그리고 3개의 버튼 모두에 대한 자바스크립트:

이 메서드는 컨테이너가 본문에 연결되지 않은 기본값인 경우에 작동합니다.

$('.foo').popover({
    title: 'Bar',
    html: true,
    content: contentHtml,
    trigger: 'manual'
}).on('shown.bs.popover', function () {
    var $popup = $(this);
    $(this).next('.popover').find('button.cancel').click(function (e) {
        $popup.popover('hide');
    });
    $(this).next('.popover').find('button.save').click(function (e) {
        $popup.popover('hide');
    });
});

용기가 '본체'에 부착되어 있을 때

그런 다음 에 설명된 아리아를 사용하여 팝업을 찾아 숨깁니다.

$('.foo').popover({
    title: 'Bar',
    html: true,
    content: contentHtml,
    container: 'body',
    trigger: 'manual'
}).on('shown.bs.popover', function (eventShown) {
    var $popup = $('#' + $(eventShown.target).attr('aria-describedby'));
    $popup.find('button.cancel').click(function (e) {
        $popup.popover('hide');
    });
    $popup.find('button.save').click(function (e) {
        $popup.popover('hide');
    });
});

저는 다른 대답들이 충분히 포괄적이지 않거나 너무 복잡하다는 것을 발견했습니다.부트스트랩 3의 경우 항상 작동해야 하는 간단한 방법은 다음과 같습니다.

$('[data-toggle="popover"]').each(function () {
    var button = $(this);
    button.popover().on('shown.bs.popover', function() {
        button.data('bs.popover').tip().find('[data-dismiss="popover"]').on('click', function () {
            button.popover('toggle');
        });
    });
});

만 하면 됩니다.data-dismiss="popover"당신의 단추 안에.사용하지 않도록 주의하시기 바랍니다.popover('hide')합니다를 할 때 popover('toggle').

이전의 예는 크게 두 가지 단점이 있습니다.

  1. '닫기' 버튼은 어떤 식으로든 참조된 요소의 ID를 인식해야 합니다.
  2. 닫기 버튼에 '클릭' 청취자인 'shown.bs .popover' 이벤트를 추가해야 합니다. 이 또한 'popover'가 표시될 때마다 해당 청취자를 추가해야 하기 때문에 좋은 해결책이 아닙니다.

아래는 그러한 단점이 없는 솔루션입니다.

기본적으로 '팝오버' 요소는 DOM에서 참조된 요소 바로 뒤에 삽입됩니다(참조된 요소와 팝오버는 즉시 형제 요소임).따라서 '닫기' 단추를 클릭하면 가장 가까운 'div.popover' 부모를 찾은 다음 바로 앞에 있는 해당 부모의 형제 요소를 찾을 수 있습니다.

닫기 버튼의 'onclick' 핸들러에서 다음 코드를 추가하기만 하면 됩니다.

$(this).closest('div.popover').popover('hide');

예:

var genericCloseBtnHtml = '<button onclick="$(this).closest(\'div.popover\').popover(\'hide\');" type="button" class="close" aria-hidden="true">&times;</button>';

$loginForm.popover({
    placement: 'auto left',
    trigger: 'manual',
    html: true,
    title: 'Alert' + genericCloseBtnHtml,
    content: 'invalid email and/or password'
});

enter image description here

제가 방금 프로젝트에 사용한 것은 다음과 같습니다.당신에게 도움이 되기를 바랍니다.

<a id="manualinputlabel" href="#" data-toggle="popover" title="weclome to use the sql quer" data-html=true  data-original-title="weclome to use the sql query" data-content="content">example</a>


$('#manualinputlabel').click(function(e) {
              $('.popover-title').append('<button id="popovercloseid" type="button" class="close">&times;</button>');
              $(this).popover();

          });

      $(document).click(function(e) {
         if(e.target.id=="popovercloseid" )
         {
              $('#manualinputlabel').popover('hide');                
         }

      });

저는 언급한 코드 예시들을 많이 확인했는데 크리스의 접근 방식은 완벽하게 작동하고 있습니다.작동하는 데모를 보여주기 위해 여기에 제 코드를 추가했습니다.

부트스트랩 3.3.1로 테스트를 해보았고 이전 버전으로는 테스트를 해보지 않았습니다.만 2.다하기 왜냐하면,shown.bs.popover이벤트는 3.x와 함께 도입되었습니다.

$(function() {
  
  var createPopover = function (item, title) {
                       
        var $pop = $(item);
        
        $pop.popover({
            placement: 'right',
            title: ( title || '&nbsp;' ) + ' <a class="close" href="#">&times;</a>',
            trigger: 'click',
            html: true,
            content: function () {
                return $('#popup-content').html();
            }
        }).on('shown.bs.popover', function(e) {
            //console.log('shown triggered');
            // 'aria-describedby' is the id of the current popover
            var current_popover = '#' + $(e.target).attr('aria-describedby');
            var $cur_pop = $(current_popover);
          
            $cur_pop.find('.close').click(function(){
                //console.log('close triggered');
                $pop.popover('hide');
            });
          
            $cur_pop.find('.OK').click(function(){
                //console.log('OK triggered');
                $pop.popover('hide');
            });
        });

        return $pop;
    };

  // create popover
  createPopover('#showPopover', 'Demo popover!');

  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

<button class="btn btn-primary edit" data-html="true" data-toggle="popover" id="showPopover">Show</button>

<div id="popup-content" class="hide">
    <p>Simple popover with a close button.</p>
    <button class="btn btn-primary OK">OK</button>
</div>

비결은 .data('bs.popover')로 현재 Popover를 가져오는 것입니다. tip():

$('#my_trigger').popover().on('shown.bs.popover', function() {
    // Define elements
    var current_trigger=$(this);
    var current_popover=current_trigger.data('bs.popover').tip();

    // Activate close button
    current_popover.find('button.close').click(function() {
        current_trigger.popover('hide');
    });
});

그냥 답을 업데이트하고 싶었을 뿐입니다.스와샤타 고쉬(Swashata Ghosh)에 따르면, 다음은 모이(moi)에서 작동하는 더 간단한 방법입니다.

HTML:

<button type="button" class="btn btn-primary example">Example</button>

JS:

$('.example').popover({
   title: function() {
      return 'Popup title' +
             '<button class="close">&times</button>';
   },
   content: 'Popup content',
   trigger: 'hover',
   html: true
});

$('.popover button.close').click(function() {
   $(this).popover('toggle');
});

이 기능은 여러 개의 팝오버에서 작동하며 중복되는 팝오버에서 발생하는 z 인덱스 문제를 처리하기 위해 추가 JS를 조금 추가했습니다.

http://jsfiddle.net/erik1337/fvE22/

자바스크립트:

var $elements = $('.my-popover');
$elements.each(function () {
    var $element = $(this);

    $element.popover({
        html: true,
        placement: 'top',
        container: $('body'), // This is just so the btn-group doesn't get messed up... also makes sorting the z-index issue easier
        content: $('#content').html()
    });

    $element.on('shown.bs.popover', function (e) {
        var popover = $element.data('bs.popover');
        if (typeof popover !== "undefined") {
            var $tip = popover.tip();
            zindex = $tip.css('z-index');

            $tip.find('.close').bind('click', function () {
                popover.hide();
            });

            $tip.mouseover(function (e) {
                $tip.css('z-index', function () {
                    return zindex + 1;
                });
            })
                .mouseout(function () {
                $tip.css('z-index', function () {
                    return zindex;
                });
            });
        }
    });
});

HTML:

<div class="container-fluid">
    <div class="well popover-demo col-md-12">
        <div class="page-header">
             <h3 class="page-title">Bootstrap 3.1.1 Popovers with a close button</h3>

        </div>
        <div class="btn-group">
            <button type="button" data-title="Popover One" class="btn btn-primary my-popover">Click me!</button>
            <button type="button" data-title="Popover Two" class="btn btn-primary my-popover">Click me!</button>
            <button type="button" data-title="Popover Three (and the last one gets a really long title!)" class="btn btn-primary my-popover">Click me!</button>
        </div>
    </div>
</div>
<div id="content" class="hidden">
    <button type="button" class="close">&times;</button>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

CSS:

/* Make the well behave for the demo */
 .popover-demo {
    margin-top: 5em
}
/* Popover styles */
 .popover .close {
    position:absolute;
    top: 8px;
    right: 10px;
}
.popover-title {
    padding-right: 30px;
}

나는 이것에 어려움을 겪고 있고 이것이 가장 간단한 방법입니다. js의 세 줄입니다.

  1. 팝업 제목에 십자가 추가
  2. js 스니펫을 사용하여 팝업을 표시하고 헤더를 클릭하여 닫습니다.
  3. 약간의 CSS를 사용해서 멋지게 만들어보세요.

enter image description here

$(document).ready(function() {
  // This is to overwrite the boostrap default and show it allways
  $('#myPopUp').popover('show');
  // This is to destroy the popover when you click the title
  $('.popover-title').click(function(){
    $('#myPopUp').popover('destroy');
  });
});
@import "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css";

/* Just to align my example */
.btn {
  margin: 90px auto;
  margin-left: 90px;
}

/* Styles for header */
.popover-title {
  border: 0;
  background: transparent;
  cursor: pointer;
  display: inline-block;
  float: right;
  text-align: right; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
<button id="myPopUp" class="btn btn-success" data-toggle="popover" data-placement="top" data-title="×" data-content="lorem ipsum content">My div or button or something with popover</button>  
 

시도해 보기:

$(function(){
  $("#example")
      .popover({
      title : 'tile',
      content : 'test'
    })
    .on('shown', function(e){
      var popover =  $(this).data('popover'),
        $tip = popover.tip();

      var close = $('<button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button>')
        .click(function(){
          popover.hide();
        });
      $('.popover-title', $tip).append(close);
    });
});

버튼을 마크업의 문자열로 추가하는 것보다 jQuery 랩핑 버튼을 사용하면 훨씬 더 깔끔하게 바인딩할 수 있기 때문에 훨씬 더 쉽습니다.부트스트랩 코드에는 안타깝게도 이 문제가 빠져 있지만, 이 해결책은 저에게 효과가 있으며, 실제로는 원하는 경우 모든 팝오버에 적용할 수 있도록 확장할 수 있습니다.

"치팅" 솔루션은 다음과 같습니다.

취소 가능한 팝업에 대한 일반적인 지침을 따릅니다.

그런 다음 CSS로 상자 안에 'X'를 집어넣습니다.

CSS:

.popover-header::after {
    content: "X";
    position: absolute;
    top: 1ex;
    right: 1ex;
}

JQuery:

$('.popover-dismiss').popover({
    trigger: 'focus'
});

HTML:

<a data-toggle="popover" data-trigger="focus" tabindex="0"  title="Native Hawaiian or Other Pacific Islander" data-content="A person having origins in any of the original peoples of Hawaii, Guam, Samoa, or other Pacific Islands.">?</a>

엄밀히 말하면 누군가가 "X"가 아닌 다른 것을 클릭하면 무시할 수 있지만 적어도 제 시나리오에서는 문제가 되지 않습니다.

$popover = $el.popover({
  html: true
  placement: 'left'
  content: 'Do you want to a <b>review</b>? <a href="#" onclick="">Yes</a> <a href="#">No</a>'
  trigger: 'manual'
  container: $container // to contain the popup code
});

$popover.on('shown', function() {
  $container.find('.popover-content a').click( function() {
    $popover.popover('destroy')
  });
});

$popover.popover('show')'
$(function(){ 
  $("#example").popover({
    placement: 'bottom',
    html: 'true',
    title : '<span class="text-info"><strong>title!!</strong></span> <button type="button" id="close" class="close">&times;</button></span>',
    content : 'test'
  })

  $(document).on('click', '#close', function (evente) {
    $("#example").popover('hide');
  });
  $("#close").click(function(event) {
    $("#example").popover('hide');
  });
});

<button type="button" id="example" class="btn btn-primary" >click</button>
    $('.tree span').each(function () {
        var $popOverThis = $(this);
        $popOverThis.popover({
            trigger: 'click',
            container: 'body',
            placement: 'right',
            title: $popOverThis.html() + '<button type="button" id="close" class="close" ">&times;</button>',
            html: true,
            content: $popOverThis.parent().children("div.chmurka").eq(0).html()
        }).on('shown.bs.popover', function (e) {
            var $element = $(this);
            $("#close").click(function () {
                $element.trigger("click");
            });
        });
    });

element를 클릭하고 팝업을 표시하면 event shown.bs .popover를 올릴 수 있습니다. 여기서 트리거를 클릭하여 팝업을 닫을 수 있는 element를 얻을 수 있습니다.

FWIW, 제가 사용하고 있는 일반 솔루션입니다.저는 부트스트랩 3을 사용하고 있지만 일반적인 접근 방식은 부트스트랩 2에서도 작동해야 한다고 생각합니다.

이 솔루션은 팝업을 활성화하고 JS 코드의 일반 블록을 사용하여 'rel="popover" 태그로 식별되는 모든 팝업에 대해 '닫기' 버튼을 추가합니다.rel="팝오버" 태그가 있어야 한다는 (표준) 요구 사항 외에 임의 수의 팝오버를 페이지에 넣을 수 있으며, 이들의 ID를 알 필요는 없습니다. 사실 이들에게는 ID가 전혀 필요 없습니다.팝오버의 제목 속성을 설정하려면 'data-title' HTML 태그 형식을 사용하고 data-html을 "true"로 설정해야 합니다.

필요하다고 생각한 요령은 팝오버 개체("po_map")에 대한 참조 색인 맵을 구축하는 것이었습니다.그런 다음 HTML을 통해 JQuery가 제공하는 인덱스("p_list['+index+')를 통해 팝오버 개체를 참조하는 'onclick' 핸들러를 추가할 수 있습니다.팝오버(\'toggle\')".이렇게 하면 JQuery에서 제공하는 고유 인덱스와 함께 객체 자체에 대한 참조 맵이 있으므로 팝업 객체의 ID에 대해 걱정할 필요가 없습니다.

자바스크립트는 다음과 같습니다.

var po_map = new Object();
function enablePopovers() {
  $("[rel='popover']").each(function(index) {
    var po=$(this);
    po_map[index]=po;
    po.attr("data-title",po.attr("data-title")+
    '<button id="popovercloseid" title="close" type="button" class="close" onclick="po_map['+index+'].popover(\'toggle\')">&times;</button>');
    po.popover({});
  });
}
$(document).ready(function() { enablePopovers() });

이 솔루션을 사용하면 사이트 전체의 모든 팝업에 손쉽게 단추를 닫을 수 있습니다.

아래의 코드는 매우 유용했습니다(https://www.emanueletessore.com/twitter-bootstrap-popover-add-close-button/) 에서 taken: taken:

$('[data-toggle="popover"]').popover({
  title: function(){
    return $(this).data('title')+'<span class="close" style="margin-top: -5px">&times;</span>';
  }
}).on('shown.bs.popover', function(e){
  var popover = $(this);
  $(this).parent().find('div.popover .close').on('click', function(e){
    popover.popover('hide');
  });
});

호버에서 끈적임, HTML:

<a href="javascript:;" data-toggle="popover" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." title="Lorem Ipsum">...</a>

자바스크립트:

$('[data-toggle=popover]').hover(function(e) {
  if( !$(".popover").is(':visible') ) {
      var el = this;
      $(el).popover('show');
      $(".popover > h3").append('<span class="close icon icon-remove"></span>')
                        .find('.close').on('click', function(e) {
                            e.preventDefault();
                            $(el).popover('hide');
                        }
      );
  }
});

제목 팝업 생성기에 이 내용을 입력합니다.

'<button class="btn btn-danger btn-xs pull-right"
onclick="$(this).parent().parent().parent().hide()"><span class="glyphicon
glyphicon-remove"></span></button>some text'

...우측 상단 모서리에 빨간색 'x' 버튼이 표시됩니다.

//$('[data-toggle=popover]').popover({title:that string here})

아직도 조금 혼란스러운 분들을 위해:

다음은 팝업을 표시한 후 팝업을 전환하고 트리거할 때 사용한 것과 동일한 버튼을 선택한 후 팝업에 .popover('toggle')를 호출하는 방법입니다.

이 경우 팝업을 닫는 코드는 다음과 같습니다.

$('#example').팝오버 ('toggle').

이에 대한 아주 간단한 해결책으로 다음과 같은 작업을 수행했습니다.

1) 다음 CSS를 추가합니다.

.sub_step_info .popover::after {
    content:url('/images/cross.png');
    position:absolute;
    display:inline-block;
    top:15px;
    right:5px;
    width:15px;
    text-align:center;
    cursor:pointer;
}

2) data-trigger="manual"

3) 그런 다음 https://github.com/twbs/bootstrap/issues/16802 을 기준으로 합니다.

$('[data-trigger="manual"]').click(function() {
    $(this).popover('toggle');
}).blur(function() {
    $(this).popover('hide');
}); 

이것은 팝업의 어느 곳에서나 클릭할 수 있다는 근거를 사용하지만, 십자가에 초점을 맞추면 여러분이 추구하는 행동을 장려할 것입니다.

저에게는 이 방법이 팝업에 닫기 버튼을 추가하는 가장 간단한 방법입니다.

HTML:

    <button type="button" id="popover" class="btn btn-primary" data-toggle="popover" title="POpover" data-html="true">
                    Show popover
    </button>

    <div id="popover-content" style="display:none"> 
       <!--Your content-->
       <button type="submit" class="btn btn-outline-primary" id="create_btn">Create</button>
       <button type="button" class="btn btn-outline-primary" id="close_popover">Cancel</button>  
    </div>

자바스크립트:

    document.addEventListener("click",function(e){
        // Close the popover 
        if (e.target.id == "close_popover"){
                $("[data-toggle=popover]").popover('hide');
            }
    });

툴팁이 펑키한 작업을 하는 문제에 부딪히다가 닫기 버튼이 클릭되었습니다.이 했습니다.span버튼을 사용하는 대신했을 때 을 두 번 .또한 닫기 버튼을 클릭했을 때 툴팁을 닫으면 다시 열리도록 하려면 툴팁을 두 번 클릭해야 합니다.이 e을 했습니다..click()아래에서 보는 방법.

<span tabindex='0' class='tooltip-close close'>×</span>

$('#myTooltip').tooltip({
    html: true,
    title: "Hello From Tooltip",
    trigger: 'click'
});    

$("body").on("click", ".tooltip-close", function (e) {
    else {
        $('.tooltip').remove();
        $('#postal-premium-tooltip').click();
    }
});

이 솔루션은 위의 @Chris 답변을 기반으로 작동하는 솔루션이지만 이후 트리거 요소를 클릭할 때 요소를 두 번 클릭할 필요가 없도록 수정되었습니다.

사용..popover('hide)는 설명에 나와 있는 대로 부트스트랩 내부 상태를 수동으로 엉망으로 만듭니다.

var closePopover = function(eventShown) {
   // Set the reference to the calling element
   var $caller = $('#' + this.id);

   // Set the reference to the popover
   var $popover = $('#' + $(eventShown.target).attr('aria-describedby'));

       // Unbind any pre-existing event handlers to prevent duplicate clicks
       $popover.find('.popover-close').off('click');

       // Bind event handler to close button
       $popover.find('.popover-close').on('click', function(e) {

          // Trigger a click on the calling element, to maintain bootstrap's internal state
          $caller.trigger('click');
        });
 }

$('.popoverTriggerElement').popover({
   trigger: 'click'
})
.on('shown.bs.popover', closePopover)

이제 Close 버튼을 사용하면 클릭 이벤트를 중복하지 않고 부트스트랩 내부 상태를 체크하여 예상대로 작동할 수 있습니다.

특정 팝업의 경우 닫기 버튼에서 클릭 이벤트를 추가할 수 있습니다.

onclick="$('#my-popover').popover('hide');

저는 부트스트랩 5를 사용하고 팝오버 안에 버튼을 넣고 싶었지만 버튼이 아무것도 작동하지 않았습니다.

여러 가지 해결책을 시도해 본 결과, 유일한 문제는 팝업의 위생 옵션이었습니다.

그래서 어쩔 수 없이.sanitize: false팝업 옵션으로 버튼을 실행할 수 있습니다.

매우 많은 답변이 있었지만, 저는 이와 같은 제약 조건을 가지고 있었지만, 이를 모두 해결한 답변은 없었습니다.

  • 부트스트랩 5와 호환 가능
  • 하나의 페이지에서 여러 개의 팝오버와 함께 작동합니다(즉, 하드코딩된 단일 ID가 없고 실제 요소 팝오버 데이터 속성을 단순하게 유지합니다).
  • 요소를 두 번 다시 클릭해야 하는 문제를 겪지 않습니다.
  • 닫지 않고 팝업 내용의 링크를 클릭할 수 있습니다.
  • 별도의 CSS는 필요 없지만, 괜찮은 것 같습니다.

올인원 코드:

$(document).ready(function() {
  $('[data-bs-toggle="popover"]').popover({
    html: true,
  }).on('shown.bs.popover', function(e) {
    // get the dom element that the popover points to
    var el = $(e.target);
    // get the popover dom obj
    var po = $('#' + el.attr('aria-describedby'));
    // get the title
    var poh = po.find('.popover-header');
    poh.append('<sup class="popover-close ms-3" style="cursor:pointer;">&times;</sup>');

    // get the close button that we just added
    var cb = poh.find('.popover-close');

    // get the bootstrap popover obj
    var bpo = bootstrap.Popover.getInstance(e.target);

    cb.on('click', function(e) {
      bpo.hide();
    });
  });
});
<html>

<head>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<body>
  <span data-bs-toggle="popover" data-bs-content="my content" id="random_id" title="my title">click this text</span>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>

</html>

<script type="text/javascript"  src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.popover-1.1.2.js"></script>

<script type="text/javascript">
$(function(){ 
$("#example").popover({
        placement: 'bottom',
        html: 'true',
        title : '<span class="text-info"><strong>title</strong></span> <button     type="button" id="close" class="close">&times;</button></span>',
        content : 'test'
    })


$("#close").click(function(event) {

$("#example").popover('hide');
});
});
</script>

<button type="button" id="example" class="btn btn-primary" >click</button>

언급URL : https://stackoverflow.com/questions/13413057/how-to-insert-close-button-in-popover-for-bootstrap