jQuery 使用 AJAX 加载 Bootstrap popover 内容。这可能吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8130069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load a Bootstrap popover content with AJAX. Is this possible?
提问by CambridgeMike
The appropriate bits of what I tried are here:
我尝试过的适当部分在这里:
<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')
})
When I click, I see the request get made, but doesn't populate the popover. I don't even see HTML for the popover get added to the DOM, but that could be firebug.
当我点击时,我看到请求被发出,但没有填充弹出窗口。我什至没有看到弹出窗口的 HTML 被添加到 DOM 中,但这可能是萤火虫。
Has anyone tried this?
有没有人试过这个?
回答by Ivan Klass
Works ok for me:
对我来说没问题:
$('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>';
}
回答by ?a?atay Gürtürk
See my blog post for the working solution: https://medium.com/cagataygurturk/load-a-bootstrap-popover-content-with-ajax-8a95cd34f6a4
有关工作解决方案,请参阅我的博客文章:https: //medium.com/cagataygurturk/load-a-bootstrap-popover-content-with-ajax-8a95cd34f6a4
First we should add a data-poload attribute to the elements you would like to add a pop over to. The content of this attribute should be the url to be loaded (absolute or relative):
首先,我们应该向要添加弹出窗口的元素添加一个 data-poload 属性。该属性的内容应该是要加载的 url(绝对或相对):
<a href="#" title="blabla" data-poload="/test.php">blabla</a>
And in JavaScript, preferably in a $(document).ready();
在 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')
prevents loading data more than once andpopover()
binds a new hover event. If you want the data to be refreshed at every hover event, you should remove the off.Please see the working JSFiddleof the example.
off('hover')
防止多次加载数据并popover()
绑定新的悬停事件。如果您希望在每次悬停事件时刷新数据,您应该删除关闭。请参阅示例的工作JSFiddle。
回答by Confusion
Having read all these solutions, I think the solution becomes much simpler if you use a synchronousajax call. You can then use something like:
阅读所有这些解决方案后,我认为如果您使用同步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');
});
回答by Alexander Chzhen
I have updated the most popular answer. But in case my changes will not be approved I put here a separate answer.
我已经更新了最受欢迎的答案。但如果我的更改不会被批准,我会在此处单独回答。
Differences are:
区别在于:
- LOADING text shown while content is loading. Very good for slow connection.
- Removed flickering which occures when mouse leaves popover first time.
- 加载内容时显示的 LOADING 文本。非常适合慢速连接。
- 消除了鼠标第一次离开弹出框时发生的闪烁。
First we should add a data-poload attribute to the elements you would like to add a pop over to. The content of this attribute should be the url to be loaded (absolute or relative):
首先,我们应该向要添加弹出窗口的元素添加一个 data-poload 属性。该属性的内容应该是要加载的 url(绝对或相对):
<a href="#" data-poload="/test.php">HOVER ME</a>
And in JavaScript, preferably in a $(document).ready();
在 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')
prevents loading data more than once and popover()
binds
a new hover event. If you want the data to be refreshed at every hover
event, you should remove the off.
off('hover')
防止多次加载数据并popover()
绑定新的悬停事件。如果您希望在每次悬停事件时刷新数据,您应该删除关闭。
Please see the working JSFiddleof the example.
请参阅示例的工作JSFiddle。
回答by Dorian Margineanu
IN 2015, this is the best answer
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')
});
回答by Asa Kusuma
A variation of the code from ?a?atay Gürtürk, you could use the delegate function instead and force hiding the popover on hoverout.
来自 ?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');
}
});
回答by fustaki
The solution of ?a?atay Gürtürk is nice but I experienced the same weirdness described by Luke The Obscure:
?a?atay Gürtürk 的解决方案很好,但我经历了与 Luke The Obscure 描述的相同的怪异:
When ajax loading lasts too much (or mouse events are too quick) we have a .popover('show') and no .popover('hide') on a given element causing the popover to remain open.
当 ajax 加载持续时间过长(或鼠标事件太快)时,我们在给定元素上有一个 .popover('show') 而没有 .popover('hide') 导致弹出窗口保持打开状态。
I preferred this massive-pre-load solution, all popover-contents are loaded and events are handled by bootstrap like in normal (static) popovers.
我更喜欢这种大规模预加载解决方案,所有弹出内容都被加载,事件由引导程序处理,就像在正常(静态)弹出窗口中一样。
$('.popover-ajax').each(function(index){
var el=$(this);
$.get(el.attr('data-load'),function(d){
el.popover({content: d});
});
});
回答by doanduyhai
Another solution:
另一种解决方案:
$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');
});
The idea here is to trigger manually the display of PopOver with mouseenter& mouseleaveevents.
这里的想法是要手动触发酥料饼的显示器的mouseenter和鼠标离开事件。
On mouseenter, if there is no PopOver created for your item (if($(this).data('popover') == null)), create it. What is interesting is that you can define your own PopOver content by passing it as argument (template) to the popover()function. Do not forget to set the htmlparameter to truealso.
上了mouseenter,如果没有您的项目创建酥料饼(如果($(本)。数据(“酥料饼”)== NULL) ),创建它。有趣的是,您可以通过将它作为参数(模板)传递给popover()函数来定义自己的 PopOver 内容。不要忘记也将html参数设置为true。
Here I just create a hidden template called popovertemplateand clone it with JQuery. Do not forget to delete the id attribute once you clone itotherwise you'll end up with duplicated ids in the DOM. Also notice that style="display: none"to hide the template in the page.
在这里,我只是创建了一个名为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>
After the creation step (or if it has been already created), you just display the popOver with $(this).popover('show');
在创建步骤之后(或者如果它已经被创建),你只需用$(this).popover('show'); 来显示 popOver ;
Then classical Ajax call. On success you need to clean the old popover content before putting new fresh data from server. How can we get the current popover content ? With the .popover.inselector! The .inclass indicates that the popover is currently displayed, that's the trick here!
然后是经典的 Ajax 调用。成功后,您需要先清理旧的 popover 内容,然后再从服务器放入新的数据。我们如何获取当前的弹出框内容?使用.popover.in选择器!的。在类指示酥料饼的当前显示,这是这里的伎俩!
To finish, on mouseleaveevent, just hide the popover.
最后,在mouseleave事件中,只需隐藏弹出框即可。
回答by drillingman
Here is my solution which works fine with ajax loaded content too.
这是我的解决方案,它也适用于 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';
}
回答by towr
If the content in the popover isn't likely to change, it would make sense to retrieve it only once. Also, some of the solutions here have the issue that if you move over multiple "previews" fast, you get multiple open popups. This solution addresses both those things.
如果弹出窗口中的内容不太可能改变,那么只检索一次是有意义的。此外,这里的一些解决方案存在的问题是,如果您快速移动多个“预览”,则会出现多个打开的弹出窗口。该解决方案解决了这两个问题。
$('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');
}
});
}
});