[英]popstate HTML 5 event being fired multiple times
Hi i am using the following code to load a part of page dynamically using jquery您好我正在使用以下代码使用 jquery 动态加载页面的一部分
loadNextBackInPage_URL = null;
function callBackFunctionLoadNextBackInPage(data)
{
//alert(data);
$("#left").fadeTo(100,1);
var data = $(data).find( '#left' );
$("#left").html(data);
if(supports_history_api())
{
history.pushState(null, null, loadNextBackInPage_URL);
window.addEventListener("popstate", function(e) {
alert('s');
loadNextBackInPage(location.pathname);
});
}
else
{
}
}
function loadNextBackInPage(url,parm)
{
//alert(url);
loadNextBackInPage_URL = url;
$("#left").fadeTo(100,.2);
$.post(url,parm,callBackFunctionLoadNextBackInPage,'html');
}
The loading part and even changing the browser URL is working.加载部分,甚至更改浏览器 URL 正在工作。 but why is the PoP state function being fired multiple times?但为什么 PoP state function 会被多次触发?
I call loadNextBackInPage() originally through an onclick function.我最初通过 onclick function 调用 loadNextBackInPage()。
I got it solved from here in codingforums我在编码论坛中从这里解决了
think you keep adding "popstate" listeners over and over...认为您一遍又一遍地添加“popstate”侦听器...
Program logic:程序逻辑:
So step 4 will be executed over and over which will register new event listeners.因此,第 4 步将一遍又一遍地执行,这将注册新的事件侦听器。 Every time "popstate" fires all the event listeners will execute每次“popstate”触发时,所有的事件监听器都会执行
Try to move the addEventListener method call out of this loop尝试将 addEventListener 方法调用移出此循环
So from those i derived a workaround and also corrected location.pathname
to location.href
所以从那些我得出一个解决方法,并将location.pathname
更正为location.href
The corrected code:更正后的代码:
loadNextBackInPage_URL = null;
popEventListnerAdded = false;
function callBackFunctionLoadNextBackInPage(data)
{
//alert(data);
$("#left").fadeTo(100,1);
var data = $(data).find( '#left' );
$("#left").html(data);
if(supports_history_api())
{
history.pushState(null, null, loadNextBackInPage_URL);
if(!popEventListnerAdded) {
window.addEventListener("popstate", function(e) {
loadNextBackInPage(location.href);
});
popEventListnerAdded = true;
}
}
else
{
}
}
function loadNextBackInPage(url,parm)
{
//alert(url);
loadNextBackInPage_URL = url;
$("#left").fadeTo(100,.2);
$.post(url,parm,callBackFunctionLoadNextBackInPage,'html');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.