我在侧边栏上使用Twitter Bootstrap的Popover功能。侧边栏每30秒被提取并重新加载一次内容。我正在起诉XMLHttpRequest,通过获取一个名为stats.hp.的文件来重新加载侧边栏的内容
下面的代码是"刷新"代码,它位于页面的标题中。
function onIndexLoad()
{
setInterval(onTimerCallback, 30000);
}
function onTimerCallback()
{
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
document.getElementById("stats").style.opacity = 0;
setTimeout(function() {
document.getElementById("stats").innerHTML = request.responseText;
document.getElementById("stats").style.opacity = 100;
}, 1000);
}
}
request.open("GET", "stats.php", true);
request.send();
}
上面的代码工作得很完美,但是,在重新加载#statsdiv之后,popover就不再做它应该做的事情了——popup。
popover代码在foreach()循环中的stats.php中,因为我需要多个popover脚本,因为侧边栏上有多个popover。
这是我的popover代码:
$(document).ready(function() {
$('a[rel=popover_$id]').popover({
placement:'right',
title:'$title',
content: $('#popover_content_$id').html()
});
});
$id
和$title
是动态的,因为它们是从foreach()循环中提取的。
如何修复它,以便在div重新加载后,popover函数将重新初始化?
$("a[rel=popover_controller_$cid]").on({
mouseenter: function () {
$('a[rel=popover_$id]').popover({
placement:'right',
title:'$title',
content: $('#popover_content_$id').html()
});
}
});
我也试过:
$("a[rel=popover_controller_$cid]").on("mouseover", function () {
$('a[rel=popover_$id]').popover({
placement:'right',
title:'$title',
content: $('#popover_content_$id').html()
});
});
.live
折旧。使用.on
委派
试试这样的东西:
$('#stats').on("mouseenter", "a[rel=popover_controller_$cid]",function () {
$('a[rel=popover_$id]').popover({
placement:'right',
title:'$title',
content: $('#popover_content_$id').html()
});
});
这将鼠标输入事件从#stats
委派到a[rel=popover_controller_$cid]
,并且由于该事件已被委派,因此在替换#stats
内容时它仍将激发。
要小心,每次鼠标悬停时都会不断初始化popover。那可能很糟糕。
当你在做这件事的时候,你应该使用jquery的ajax,而不是原生的xhr。它更容易,更跨浏览器。
$.get('stats.php', function(d){
$('#stats').html(d);
};
--
setInterval(function(){
$.get('stats.php', function(data) {
$('#stats').html(data);
});
}, 30000);