我正在使用以下代码在我的产品上显示“弹出”效果。弹出框的内容来自 Ajax。这是使用Twitter Bootstrap 弹出框。是否可以只进行一次 Ajax 调用?现在,每次我将鼠标悬停在产品上时,都会再次发送请求。我想调整这段代码,所以如果内容已经被获取,使用它并且不要发出另一个请求。
谢谢
$(document).ready(function(){
//Quick view boxes
var overPopup = false;
$("a[rel=popover]", '.favorites').popover({
trigger: 'manual',
placement: 'bottom',
html: true,
content: function(){
var div_id = "div-id-" + $.now();
return details_in_popup(div_id, $(this).data('product-id'));
}
}).mouseover(function (e) {
// when hovering over an element which has a popover, hide
// them all except the current one being hovered upon
$('[rel=popover]').not('[data-unique="' + $(this).data('unique') + '"]').popover('hide');
var $popover = $(this);
$popover.popover('show');
$popover.data('popover').tip().mouseenter(function () {
overPopup = true;
}).mouseleave(function () {
overPopup = false;
$popover.popover('hide');
});
}).mouseout(function (e) {
// on mouse out of button, close the related popover
// in 200 milliseconds if you're not hovering over the popover
var $popover = $(this);
setTimeout(function () {
if (!overPopup) {
$popover.popover('hide');
}
}, 200);
});
});
function details_in_popup(div_id, product_id){
$.ajax({
url: 'index.php?route=product/product/get_product_ajax',
type: 'post',
data: 'product_id=' + product_id,
dataType: 'json',
success: function(json){
if (json['success']) {
$('#' + div_id).html(json['success']);
}
}
});
return '<div id="'+ div_id +'">Loading...</div>';
}
这是我的 html 结构的样子:
<div class="image">
<a data-unique="unique-3" data-product-id="39" rel="popover" href="link to product">
<img src="path to image" />
</a>
</div>
更新:
感谢大家的帮助和意见。这是我修复它的方法:
function details_in_popup(div_id, product_id){
//I added this block
if ( $("#popover_content_for_prod_" + product_id).length ) {
return $("#popover_content_for_prod_" + product_id).html();
}
$.ajax({
url: 'index.php?route=product/product/get_product_ajax',
type: 'post',
data: 'product_id=' + product_id,
dataType: 'json',
success: function(json){
if (json['success']) {
$('#' + div_id).html(json['success']);
//Also added this line
$('body').append('<div style="display:none;" id="popover_content_for_prod_' + product_id + '">' + json['success'] + '</div>');
}
}
});
return '<div id="'+ div_id +'">Loading...</div>';
}