【问题标题】:Load a Bootstrap popover content with AJAX. Is this possible?使用 AJAX 加载 Bootstrap 弹出内容。这可能吗?
【发布时间】:2011-12-29 03:02:40
【问题描述】:

我尝试过的适当部分在这里:

<a href="#" data-content="<div id='my_popover'></div>"> Click here </a>

$(".button").popover({html: true})

$(".button").click(function(){
    $(this).popover('show');
    $("#my_popover").load('my_stuff')
})

单击时,我看到请求已发出,但未填充弹出框。我什至没有看到将弹出框的 HTML 添加到 DOM,但这可能是萤火虫。

有人试过吗?

【问题讨论】:

  • 我没有使用过引导程序,但我想当您尝试向其添加内容时该元素可能不存在,但这是一个猜测。您是否收到任何 javascript 错误?
  • 如果您有多个弹出框并希望为每个弹出框加载 不同 内容,那么这个答案非常简洁,可以让您保留很多开箱即用的设置对于弹出框 - 您需要做的就是将弹出框的 ID 存储在链接的属性上,并在 'shown.bs.popover' 处理程序中读取它们:stackoverflow.com/a/39028723/1371408

标签: jquery twitter-bootstrap


【解决方案1】:

对我来说没问题:

$('a.popup-ajax').popover({
    "html": true,
    "content": function(){
        var div_id =  "tmp-id-" + $.now();
        return details_in_popup($(this).attr('href'), div_id);
    }
});

function details_in_popup(link, div_id){
    $.ajax({
        url: link,
        success: function(response){
            $('#'+div_id).html(response);
        }
    });
    return '<div id="'+ div_id +'">Loading...</div>';
}

【讨论】:

  • 天才回答!这就是为什么编辑它以使其更具可读性
  • 很好的解决方案。然而,使用当前版本的引导程序,似乎 der 可能是这种方法 github.com/twbs/bootstrap/issues/12563 的一些问题。我遇到了两次问题,快速的解决方案是确保每个弹出窗口中都有一个标题。这也意味着我实际上从未看到您正在使用的加载文本。
  • 工作,除了我必须使用数据链接而不是href,当使用href时,我的浏览器只会在新窗口中打开href中的url。
  • 这不会导致对齐问题吗?在 3.3.1 上使用这种方法(并使用 Chrome)时,弹出框会在显示“正在加载...”时自行对齐,但是一旦加载了弹出框的真实内容,对齐方式就不会相应调整。 .
  • 不错的解决方案。此解决方案的一个缺点是 ajax 调用进行了两次。 popover 组件是一个工具提示,它首先使用 hasContent 检查内容,然后使用 setContent 获取内容。
【解决方案2】:

请参阅我的博客文章了解有效的解决方案:https://medium.com/cagataygurturk/load-a-bootstrap-popover-content-with-ajax-8a95cd34f6a4

首先我们应该为你想要的元素添加一个 data-poload 属性 喜欢添加一个弹出窗口。该属性的内容应该是 要加载的url(绝对或相对):

<a href="#" title="blabla" data-poload="/test.php">blabla</a>

在 JavaScript 中,最好是在 $(document).ready();

$('*[data-poload]').hover(function() {
    var e=$(this);
    e.off('hover');
    $.get(e.data('poload'),function(d) {
        e.popover({content: d}).popover('show');
    });
});

off('hover') 防止多次加载数据,popover() 绑定 一个新的悬停事件。如果您希望在每次悬停时刷新数据 事件,你应该删除关闭。

请查看示例的工作JSFiddle

【讨论】:

  • 在 ajax 调用完成之前,当我将鼠标悬停两次时,我感到有些奇怪......我的弹出框会“粘住”打开。我通过将“el.unbind('hover')”移动到 $.get() 之前解决了这个问题。
  • 这行得通,但弹出框也适合我,即使取消绑定是在 get 之前
  • 如果您尝试加载外部 URL,您将遇到跨域访问限制。为了解决这个问题,您可以将弹出框的html 属性设置为true,然后将content 属性设置为iframe HTML 标记,例如content: '&lt;iframe src="http://www.google.com"&gt;&lt;/iframe&gt;'。您还需要使用 CSS 覆盖弹出框的 max-width 属性,并且很可能还需要使用 CSS 删除 iframe 的样式。
  • @FrzKhan 你可以使用e.off('hover') 方法
  • 这不起作用,因为 stackoverflow.com/questions/4111194/… 更改为 .hover(function(){}) 有效。
【解决方案3】:

阅读了所有这些解决方案后,我认为如果您使用 同步 ajax 调用,解决方案会变得更加简单。然后你可以使用类似的东西:

  $('#signin').popover({
    html: true,
    trigger: 'manual',
    content: function() {
      return $.ajax({url: '/path/to/content',
                     dataType: 'html',
                     async: false}).responseText;
    }
  }).click(function(e) {
    $(this).popover('toggle');
  });

【讨论】:

  • 这帮了我很多忙,因为在 ajax 返回内容之前,我在某个位置出现了弹出框渲染问题(导致它从屏幕上加载)。谢谢先生!
  • 它可能更简单,但也没有@Ivan Klass 发布的解决方案那么优雅。
  • async: false 为我杀了这个
  • 虽然 JavaScript 和同步代码确实更容易,但并不能很好地结合在一起。由于 JavaScript 是单线程的,只要请求需要,这将阻止任何代码执行。
  • 不推荐使用同步 AJAX。
【解决方案4】:

我更新了最受欢迎的答案。但如果我的更改不会被批准,我会在此处单独提供一个答案。

区别是:

  • 加载内容时显示正在加载的文本。非常适合慢速连接。
  • 删除了鼠标第一次离开弹出框时发生的闪烁。

首先我们应该为你想要的元素添加一个 data-poload 属性 喜欢添加一个弹出窗口。该属性的内容应该是 要加载的url(绝对或相对):

<a href="#" data-poload="/test.php">HOVER ME</a>

在 JavaScript 中,最好是在 $(document).ready();

 // On first hover event we will make popover and then AJAX content into it.
$('[data-poload]').hover(
    function (event) {
        var el = $(this);

        // disable this event after first binding 
        el.off(event);

        // add initial popovers with LOADING text
        el.popover({
            content: "loading…", // maybe some loading animation like <img src='loading.gif />
            html: true,
            placement: "auto",
            container: 'body',
            trigger: 'hover'
        });

        // show this LOADING popover
        el.popover('show');

        // requesting data from unsing url from data-poload attribute
        $.get(el.data('poload'), function (d) {
            // set new content to popover
            el.data('bs.popover').options.content = d;

            // reshow popover with new content
            el.popover('show');
        });
    },
    // Without this handler popover flashes on first mouseout
    function() { }
);

off('hover') 防止多次加载数据并且popover() 绑定 一个新的悬停事件。如果您希望在每次悬停时刷新数据 事件,你应该删除关闭。

请查看示例的工作JSFiddle

【讨论】:

    【解决方案5】:

    2015 年,这是最好的答案

    $('.popup-ajax').mouseenter(function() {
       var i = this
       $.ajax({
          url: $(this).attr('data-link'), 
          dataType: "html", 
          cache:true, 
          success: function( data{
             $(i).popover({
                html:true,
                placement:'left',
                title:$(i).html(),
                content:data
             }).popover('show')
          }
       })
    });
    
    $('.popup-ajax').mouseout(function() {
      $('.popover:visible').popover('destroy')
    });
    

    【讨论】:

      【解决方案6】:

      来自 Çağatay Gürtürk 的代码变体,您可以改用委托函数并在悬停时强制隐藏弹出框。

      $('body').delegate('.withajaxpopover','hover',function(event){
          if (event.type === 'mouseenter') {
              var el=$(this);
              $.get(el.attr('data-load'),function(d){
                  el.unbind('hover').popover({content: d}).popover('show');
              });
          }  else {
              $(this).popover('hide');
          }
      });
      

      【讨论】:

      • 对于最近的 jquery : $('*[data-poload]').on('mouseenter mouseleave', function(event) {
      【解决方案7】:

      Çağatay Gürtürk 的解决方案很好,但我遇到了 Luke The Obscure 所描述的同样怪异:

      当 ajax 加载持续时间过长(或鼠标事件太快)时,我们在给定元素上有一个 .popover('show') 而没有 .popover('hide') 会导致弹出框保持打开状态。

      我更喜欢这种大规模预加载解决方案,所有弹出框内容都已加载,事件由引导程序处理,就像在正常(静态)弹出框中一样。

      $('.popover-ajax').each(function(index){
      
          var el=$(this);
      
          $.get(el.attr('data-load'),function(d){
              el.popover({content: d});       
          });     
      
      });
      

      【讨论】:

        【解决方案8】:

        另一种解决方案:

        $target.find('.myPopOver').mouseenter(function()
        {
            if($(this).data('popover') == null)
            {
                $(this).popover({
                    animation: false,
                    placement: 'right',
                    trigger: 'manual',
                    title: 'My Dynamic PopOver',
                    html : true,
                    template: $('#popoverTemplate').clone().attr('id','').html()
                });
            }
            $(this).popover('show');
            $.ajax({
                type: HTTP_GET,
                url: "/myURL"
        
                success: function(data)
                {
                    //Clean the popover previous content
                    $('.popover.in .popover-inner').empty();    
        
                    //Fill in content with new AJAX data
                    $('.popover.in .popover-inner').html(data);
        
                }
            });
        
        });
        
        $target.find('.myPopOver').mouseleave(function()
        {
            $(this).popover('hide');
        });
        

        这里的想法是通过 mouseentermouseleave 事件手动触发 PopOver 的显示。

        mouseenter 上,如果没有为您的项目创建 PopOver (if($(this).data('popover') == null)),请创建它。有趣的是,您可以通过将其作为参数 (template) 传递给 popover() 函数来定义自己的 PopOver 内容。不要忘记将 html 参数也设置为 true

        这里我只是创建了一个名为 popovertemplate 的隐藏模板,并用 JQuery 克隆它。 克隆后不要忘记删除 id 属性,否则您最终会在 DOM 中得到重复的 id。还要注意 style="display: none" 将模板隐藏在页面中。

        <div id="popoverTemplateContainer" style="display: none">
        
            <div id="popoverTemplate">
                <div class="popover" >
                    <div class="arrow"></div>
                    <div class="popover-inner">
                        //Custom data here
                    </div>
                </div>
            </div>
        </div>
        

        在创建步骤之后(或者如果它已经创建),您只需使用 $(this).popover('show'); 显示 popOver;

        然后是经典的 Ajax 调用。成功后,您需要在从服务器放入新的新数据之前清理旧的弹出框内容。我们如何获取当前的弹出框内容?使用 .popover.in 选择器! .in 类表示弹出框当前已显示,这就是这里的技巧!

        要完成,在 mouseleave 事件中,只需隐藏弹出框即可。

        【讨论】:

        • 对我来说也是一样,最简单和最好的一个;-)
        • 问题在于每次悬停时您都从服务器请求数据。它应该只加载一次数据。
        • @Richard Torcato 一方面你是对的。不过,将结果放入缓存应该很容易。另一方面,也许我们确实想在每次悬停时访问服务器以加载新数据。所以由你来实现缓存
        • 我意识到这已经过时了,但是如果有人在看这个,我无法想象如果你有多个弹出窗口并且滚动它们中的每一个,它会很好地工作。悬停在 A 上,为 A 发送请求,悬停在 B 上并保持悬停,为 B 发送请求,来自 B 的响应到达,更新 B 的弹出框,A 的响应到达,更新 B 的弹出框 (因为成功功能只会清除该类的任何内容。查看此内容以补充上述内容可能会有所帮助stackoverflow.com/a/34030999/2524589
        【解决方案9】:

        这里的答案太多了,但我也发现没有一个是我想要的。我已经扩展了 Ivan Klass 的答案,使其既适合 Bootstrap 4 又可以智能缓存。

        请注意,由于 Stackoverflow 的 CORS 策略,sn-p 实际上不会加载远程地址。

        var popoverRemoteContents = function(element) {
          if ($(element).data('loaded') !== true) {
            var div_id = 'tmp-id-' + $.now();
            $.ajax({
              url: $(element).data('popover-remote'),
              success: function(response) {
                $('#' + div_id).html(response);
                $(element).attr("data-loaded", true);
                $(element).attr("data-content", response);
                return $(element).popover('update');
              }
            });
            return '<div id="' + div_id + '">Loading...</div>';
          } else {
            return $(element).data('content');
          }
        };
        
        $('[data-popover-remote]').popover({
          html: true,
          trigger: 'hover',
          content: function() {
            return popoverRemoteContents(this);
          }
        });
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
        
        <span data-popover-remote="http://example.com/">Remote Popover test with caching</span>

        【讨论】:

        • 我能够轻松地将其调整为我需要的解决方案。谢谢!
        • 很好的解决方案,只需在弹出框配置中添加“sanitize: false”来处理我的css!
        【解决方案10】:

        这是我的解决方案,它也适用于 ajax 加载的内容。

        /*
         * popover handler assigned document (or 'body') 
         * triggered on hover, show content from data-content or 
         * ajax loaded from url by using data-remotecontent attribute
         */
        $(document).popover({
            selector: 'a.preview',
            placement: get_popover_placement,
            content: get_popover_content,
            html: true,
            trigger: 'hover'
        });
        
        function get_popover_content() {
            if ($(this).attr('data-remotecontent')) {
                // using remote content, url in $(this).attr('data-remotecontent')
                $(this).addClass("loading");
                var content = $.ajax({
                    url: $(this).attr('data-remotecontent'),
                    type: "GET",
                    data: $(this).serialize(),
                    dataType: "html",
                    async: false,
                    success: function() {
                        // just get the response
                    },
                    error: function() {
                        // nothing
                    }
                }).responseText;
                var container = $(this).attr('data-rel');
                $(this).removeClass("loading");
                if (typeof container !== 'undefined') {
                    // show a specific element such as "#mydetails"
                    return $(content).find(container);
                }
                // show the whole page
                return content;
            }
            // show standard popover content
            return $(this).attr('data-content');
        }
        
        function get_popover_placement(pop, el) {
            if ($(el).attr('data-placement')) {
                return $(el).attr('data-placement');
            }
            // find out the best placement
            // ... cut ...
            return 'left';
        }
        

        【讨论】:

          【解决方案11】:

          如果弹出窗口中的内容不太可能更改,则只检索一次是有意义的。此外,这里的一些解决方案存在这样一个问题,即如果您快速移动多个“预览”,您将获得多个打开的弹出窗口。 此解决方案解决了这两个问题。

          $('body').on('mouseover', '.preview', function() 
          {
              var e = $(this);
              if (e.data('title') == undefined)
              {
                  // set the title, so we don't get here again.
                  e.data('title', e.text());
          
                  // set a loader image, so the user knows we're doing something
                  e.data('content', '<img src="/images/ajax-loader.gif" />');
                  e.popover({ html : true, trigger : 'hover'}).popover('show');
          
                  // retrieve the real content for this popover, from location set in data-href
                  $.get(e.data('href'), function(response)
                  {
                      // set the ajax-content as content for the popover
                      e.data('content', response.html);
          
                      // replace the popover
                      e.popover('destroy').popover({ html : true, trigger : 'hover'});
          
                      // check that we're still hovering over the preview, and if so show the popover
                      if (e.is(':hover'))
                      {
                          e.popover('show');
                      }
                  });
              }
          });
          

          【讨论】:

            【解决方案12】:

            我认为我的解决方案使用默认功能更简单。

            http://jsfiddle.net/salt/wbpb0zoy/1/

            $("a.popover-ajax").each(function(){
            		 $(this).popover({
            			trigger:"focus",
            			placement: function (context, source) {
                              var obj = $(source);
            				  $.get(obj.data("url"),function(d) {
                                    $(context).html( d.titles[0].title)
                              });	
            			},
            			html:true,
            			content:"loading"
            		 });
            });
            <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
            
            
            <ul class="list-group">
              <li class="list-group-item"><a href="#" data-url="https://tr.instela.com/api/v2/list?op=today" class="popover-ajax">Cras justo odio</a></li>
              <li class="list-group-item"><a href="#" data-url="https://tr.instela.com/api/v2/list?op=today" class="popover-ajax">Dapibus ac facilisis in</a></li>
              <li class="list-group-item"><a href="#" data-url="https://tr.instela.com/api/v2/list?op=today" class="popover-ajax">Morbi leo risus</a></li>
              <li class="list-group-item"><a href="#" data-url="https://tr.instela.com/api/v2/list?op=today" class="popover-ajax">Porta ac consectetur ac</a></li>
              <li class="list-group-item"><a href="#" data-url="https://tr.instela.com/api/v2/list?op=today" class="popover-ajax">Vestibulum at eros</a></li>
            </ul>

            【讨论】:

              【解决方案13】:

              在此线程中给出了与此类似的答案:Setting data-content and displaying popover - 这是一种更好的方式来实现您希望实现的目标。否则,您将不得不在 popover 方法的选项中使用 live: true 选项。希望这会有所帮助

              【讨论】:

                【解决方案14】:

                我尝试了 Çağatay Gürtürk 的解决方案,但得到了与 Luke the Obscure 相同的怪异之处。然后尝试了 Asa Kusuma 的解决方案。这可行,但我相信它会在显示弹出框时每次读取 Ajax。对 unbind('hover') 的调用无效。这是因为委托正在监视特定类中的事件——但该类没有改变。

                这是我的解决方案,非常基于 Asa Kusuma 的解决方案。变化:

                • delegate 替换为 on 以匹配新的 JQuery 库。
                • 删除“withajaxpopover”类而不是取消绑定悬停事件(从未绑定)
                • 将“触发器:悬停”添加到弹出框,以便 Bootstrap 将在第二次使用时完全处理它。
                • 我的数据加载函数返回 JSon,这样可以很容易地为弹出框指定标题和内容。
                /* 目标:显示一个工具提示/弹出框,其中的内容是从 仅限第一次申请。 如何:获取适当的内容并在第一时间注册工具提示/弹出框 鼠标进入一个带有“withajaxpopover”类的 DOM 元素。除掉 class 从元素中提取,所以下次鼠标进入时我们不会这样做。 但是,这并没有第一次显示工具提示/弹出框 (因为注册工具提示时鼠标已经进入)。 所以我们必须自己显示/隐藏它。 */ $(函数(){ $('body').on('hover', '.withajaxpopover', function(event){ if (event.type === 'mouseenter') { 变量 el=$(这个); $.get(el.attr('data-load'),function(d){ el.removeClass('withajaxpopover') el.popover({触发器:'悬停', 标题:d.title, 内容:d.content}).popover('show'); }); } 别的 { $(this).popover('hide'); } }); });

                【讨论】:

                  【解决方案15】:

                  我在这里尝试了一些建议,我想提出我的建议(这有点不同) - 我希望它会对某人有所帮助。我想在第一次点击时显示弹出窗口并在第二次点击时隐藏它(当然每次都更新数据)。 我使用了一个额外的变量visable 来了解弹出框是否可见。 这是我的代码: HTML:

                  <button type="button" id="votingTableButton" class="btn btn-info btn-xs" data-container="body" data-toggle="popover" data-placement="left" >Last Votes</button>
                  

                  Javascript:

                  $('#votingTableButton').data("visible",false);
                  
                  $('#votingTableButton').click(function() {  
                  if ($('#votingTableButton').data("visible")) {
                      $('#votingTableButton').popover("hide");
                      $('#votingTableButton').data("visible",false);          
                  }
                  else {
                      $.get('votingTable.json', function(data) {
                          var content = generateTableContent(data);
                          $('#votingTableButton').popover('destroy');
                          $('#votingTableButton').popover({title: 'Last Votes', 
                                                  content: content, 
                                                  trigger: 'manual',
                                                  html:true});
                          $('#votingTableButton').popover("show");
                          $('#votingTableButton').data("visible",true);   
                      });
                  }   
                  });
                  

                  干杯!

                  【讨论】:

                    【解决方案16】:

                    这是解决一些问题的方法:

                    1. 更新内容后出现对齐问题,尤其是在展示位置为“顶部”时。关键是调用._popper.update(),它会重新计算弹出框的位置。
                    2. 内容更新后的宽度变化。它不会破坏任何东西,它只是看起来对用户来说很刺耳。为了减少这种情况,我将弹出框的宽度设置为 100%(然后以 max-width 为上限)。
                    var e = $("#whatever");
                    e.popover({
                        placement: "top",
                        trigger: "hover",
                        title: "Test Popover",
                        content: "<span class='content'>Loading...</span>",
                        html: true
                    }).on("inserted.bs.popover", function() {
                        var popover = e.data('bs.popover');
                        var tip = $(popover.tip);
                        tip.css("width", "100%");
                        $.ajax("/whatever")
                            .done(function(data) {
                                tip.find(".content").text(data);
                                popover._popper.update();
                            }).fail(function() {
                                tip.find(".content").text("Sorry, something went wrong");
                            });
                    });
                    

                    【讨论】:

                    • 我喜欢这些概念,但不幸的是它们对我不起作用...(即位置更新和 100% 宽度)不确定这些是否随着 Bootstrap 4 发生了变化?
                    • 100% 的宽度可能取决于您的元素的布局方式......也许。内容加载后框是否还在变宽?
                    • 对于该位置,您可以在popover._popper.update() 处设置断点,并确保popover_popperupdate 都具有预期值。这些当然有可能发生了变化。
                    • 右 - 新内容后框变宽。我尝试将一些值写入控制台,但结果未定义。
                    • - 你是对的。原来我试图同时做一些更复杂的事情,但它没有用。但现在我也能够将它纳入其中。这是一个小提琴:jsfiddle.net/udfz5wrv/1 使您能够使用选择器(如果您需要绑定处理程序等)、从选择器访问数据、显示引导加载微调器等。
                    【解决方案17】:
                    $("a[rel=popover]").each(function(){
                            var thisPopover=$(this);
                                    var thisPopoverContent ='';
                                    if('you want a data inside an html div tag') {
                                    thisPopoverContent = $(thisPopover.attr('data-content-id')).html();
                                    }elseif('you want ajax content') {
                                        $.get(thisPopover.attr('href'),function(e){
                                            thisPopoverContent = e;
                                        });
                                }
                            $(this).attr(   'data-original-title',$(this).attr('title') );
                            thisPopover.popover({
                                content: thisPopoverContent
                            })
                            .click(function(e) {
                                e.preventDefault()
                            });
                    
                        });
                    

                    请注意,我使用了相同的 href 标记并使其在单击时不会更改页面,这对于 SEO 以及如果用户没有 javascript 也是一件好事!

                    【讨论】:

                      【解决方案18】:

                      我喜欢 Çağatay 的解决方案,但我的弹出窗口并没有隐藏在 mouseout 上。我用这个添加了这个额外的功能:

                      // hides the popup
                      $('*[data-poload]').bind('mouseout',function(){
                         var e=$(this);
                         e.popover('hide'); 
                      });
                      

                      【讨论】:

                        【解决方案19】:

                        我使用了原始解决方案,但做了一些更改:

                        首先,我使用getJSON() 而不是get(),因为我正在加载一个json 脚本。接下来我添加了悬停的触发行为来解决粘弹问题。

                        $('*[data-poload]').on('mouseover',function() {
                            var e=$(this);
                            $.getJSON(e.data('poload'), function(data){
                                var tip;
                                $.each(data, function (index, value) {
                                   tip = this.tip;
                                   e.popover({content: tip, html: true, container: 'body', trigger: 'hover'}).popover('show');
                                });
                            });
                        });
                        

                        【讨论】:

                          【解决方案20】:

                          我添加了 html: true,因此它不会显示原始 html 输出,以防您想格式化结果。您还可以添加更多控件。

                              $('*[data-poload]').bind('click',function() {
                                  var e=$(this);
                                  e.unbind('click');
                                  $.get(e.data('poload'),function(d) {
                                      e.popover({content: d, html: true}).popover('show', {
                          
                                      });
                                  });
                              });
                          

                          【讨论】:

                            【解决方案21】:

                            使用悬停触发器在静态元素上显示 ajax 弹出框:

                            $('.hover-ajax').popover({
                                "html": true,
                                trigger: 'hover',
                                "content": function(){
                                    var div_id =  "tmp-id-" + $.now();
                                    return details_in_popup($(this).attr('href'), div_id);
                                }
                            });
                            
                            function details_in_popup(link, div_id){
                                $.ajax({
                                    url: link,
                                    success: function(response){
                                        $('#'+div_id).html(response);
                                    }
                                });
                                return '<div id="'+ div_id +'">Loading...</div>';
                            }
                            

                            HTML:

                            <span class="hover-ajax" href="http://domain.tld/file.php"> Hey , hoover me ! </span>
                            

                            【讨论】:

                              【解决方案22】:
                                $('[data-poload]').popover({
                                  content: function(){
                                    var div_id =  "tmp-id-" + $.now();
                                    return details_in_popup($(this).data('poload'), div_id, $(this));
                                  },
                                  delay: 500,
                              
                                  trigger: 'hover',
                                  html:true
                                });
                              
                                function details_in_popup(link, div_id, el){
                                    $.ajax({
                                        url: link,
                                        cache:true,
                                        success: function(response){
                                            $('#'+div_id).html(response);
                                            el.data('bs.popover').options.content = response;
                                        }
                                    });
                                    return '<div id="'+ div_id +'"><i class="fa fa-spinner fa-spin"></i></div>';
                                }   
                              

                              Ajax 内容加载一次!见el.data('bs.popover').options.content = response;

                              【讨论】:

                                【解决方案23】:

                                我做到了,它与 ajax 和加载弹出内容非常完美。

                                var originalLeave = $.fn.popover.Constructor.prototype.leave;
                                        $.fn.popover.Constructor.prototype.leave = function(obj){
                                            var self = obj instanceof this.constructor ?
                                                obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
                                            var container, timeout;
                                
                                            originalLeave.call(this, obj);
                                
                                            if(obj.currentTarget) {
                                                container = $(obj.currentTarget).siblings('.popover')
                                                timeout = self.timeout;
                                                container.one('mouseenter', function(){
                                                    //We entered the actual popover – call off the dogs
                                                    clearTimeout(timeout);
                                                    //Let's monitor popover content instead
                                                    container.one('mouseleave', function(){
                                                        $.fn.popover.Constructor.prototype.leave.call(self, self);
                                                    });
                                                })
                                            }
                                        };
                                        var attr = 'tooltip-user-id';
                                        if ($('a['+ attr +']').length)
                                            $('a['+ attr +']').popover({
                                                html: true,
                                                trigger: 'click hover',
                                                placement: 'auto',
                                                content: function () {
                                                    var this_ = $(this);
                                                    var userId = $(this).attr(attr);
                                                    var idLoaded = 'tooltip-user-id-loaded-' + userId;
                                                    var $loaded = $('.' + idLoaded);
                                                    if (!$loaded.length) {
                                                        $('body').append('<div class="'+ idLoaded +'"></div>');
                                                    } else if ($loaded.html().length) {
                                                        return $loaded.html();
                                                    }
                                                    $.get('http://example.com', function(data) {
                                                        $loaded.html(data);
                                                        $('.popover .popover-content').html(data);
                                                        this_.popover('show');
                                                    });
                                                    return '<img src="' + base_url + 'assets/images/bg/loading.gif"/>';
                                                },
                                                delay: {show: 500, hide: 1000},
                                                animation: true
                                            });
                                

                                您可以查看http://kienthuchoidap.com。转到此并将鼠标悬停到用户的用户名。

                                【讨论】:

                                  【解决方案24】:
                                  <button type="button" id="popover2" title="" data-content="<div id='my_popover' style='height:250px;width:300px;overflow:auto;'>Loading...Please Wait</div>" data-html="true" data-toggle="popover2" class="btn btn-primary" data-original-title="A Title">Tags</button>
                                  
                                  $('#popover2').popover({ 
                                      html : true,
                                      title: null,
                                      trigger: "click",
                                      placement:"right"
                                  });
                                  
                                  $("#popover2").on('shown.bs.popover', function(){
                                      $('#my_popover').html("dynamic content loaded");
                                  
                                  });
                                  

                                  【讨论】:

                                    【解决方案25】:

                                    对我来说,在加载弹出框之前更改数据内容:

                                    $('.popup-ajax').data('content', function () {
                                        var element = this;
                                        $.ajax({
                                            url: url,
                                            success: function (data) {
                                    
                                                $(element).attr('data-content', data)
                                    
                                                $(element).popover({
                                                    html: true,
                                                    trigger: 'manual',
                                                    placement: 'left'
                                                });
                                                $(element).popover('show')
                                            }})
                                    })
                                    

                                    【讨论】:

                                      【解决方案26】:

                                      这对我有用,此代码修复了可能的对齐问题:

                                      <a class="ajax-popover" data-container="body" data-content="Loading..." data-html="data-html" data-placement="bottom" data-title="Title" data-toggle="popover" data-trigger="focus" data-url="your_url" role="button" tabindex="0" data-original-title="" title="">
                                        <i class="fa fa-info-circle"></i>
                                      </a>
                                      
                                      $('.ajax-popover').click(function() {
                                        var e = $(this);
                                        if (e.data('loaded') !== true) {
                                          $.ajax({
                                            url: e.data('url'),
                                            dataType: 'html',
                                            success: function(data) {
                                              e.data('loaded', true);
                                              e.attr('data-content', data);
                                              var popover = e.data('bs.popover');
                                              popover.setContent();
                                              popover.$tip.addClass(popover.options.placement);
                                              var calculated_offset = popover.getCalculatedOffset(popover.options.placement, popover.getPosition(), popover.$tip[0].offsetWidth, popover.$tip[0].offsetHeight);
                                              popover.applyPlacement(calculated_offset, popover.options.placement);
                                            },
                                            error: function(jqXHR, textStatus, errorThrown) {
                                              return instance.content('Failed to load data');
                                            }
                                          });
                                        }
                                      });
                                      

                                      以防万一,我使用的端点返回 html(rails 部分)

                                      我从这里https://stackoverflow.com/a/13565154/3984542获取了部分代码

                                      【讨论】:

                                        猜你喜欢
                                        • 2014-06-09
                                        • 2012-05-30
                                        • 2014-02-22
                                        • 2013-12-05
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2019-11-06
                                        • 2011-05-26
                                        相关资源
                                        最近更新 更多