繁体   English   中英

主页加载两次onpopstate

[英]Home page load two time onpopstate

我已经用PHP制作了一个ajax #container div,包括:

 <div id="container"> <?php $d="pages/"; if(isset($_GET['p'])){ $p=strtolower($_GET['p']); if(preg_match("/^[a-z0-9\\-]+$/",$p) && file_exists($d.$p.".html")){ include $d.$p.".html"; } else{ include $d."404.html"; } } ?> </div> 

我使用onpopstate(当我的状态为null时,加载home.html,否则加载历史记录页面)来模拟历史记录。 问题是当我的页面状态为state = null(第一页加载)时,由于包含,我的页面两次加载,我该如何解决? 这是我的ajax:

 var afficher = function ( data, page ) { $( '#container' ).delay ( 300 ).fadeOut ( 400, function () { $( '#container' ).empty (); $( '#container' ).append ( data ); $( '#container' ).fadeIn ( 500, function (){ } ); } ); }; var loadPage = function ( page, storeHistory ) { if ( typeof storeHistory === 'undefined' ) { var storeHistory = true; } $.ajax ( { url: 'pages/' + page, cache: false, success: function ( html ) { afficher ( html, page ); if ( storeHistory === true ) { history.pushState ( { 'key': 'value', 'url': page }, '', page ); } }, error: function ( XMLHttpRequest, textStatus, errorThrown ) { afficher ( 'erreur lors du chagement de la page' ); } } ); return false; }; window.onpopstate = function ( e ) { if ( e.state === null ) { loadPage ( 'home.html' ); } else { loadPage ( e [ 'state' ] [ 'url' ], false ); } }; $( document ).ready ( function () { $( '#menu a' ).on ( 'click',function ( e ) { var page = $( this ).attr ( 'href' ); loadPage ( page ); return false; } ); $( '#container' ).on ( 'click', '.vs-transform a', function () { var page = $( this ).attr ( 'href' ); loadPage ( page ); return false; } ); } ); 

在某些浏览器中,页面加载被视为popstate事件。 您需要将绑定popstate事件推迟到页面加载之后:

window.addEventListener('load', function() {
    setTimeout(function() {
        window.addEventListener('popstate', function() {
            //do stuff
        });
    }, 0);
});

这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM