前のページを読み込まないのはなぜですか、そしてURLを変更する方法は?

StackOverflow https://stackoverflow.com/questions/20353109

  •  25-08-2022
  •  | 
  •  

質問

仮定:1.phpをクリックしてから2.phpをクリックしてから3.phpを押してください。 URLとバックのサポートも変更したいので、SEOフレンドリーになることができます。

<pre>
<html>
<head>
    <script type="text/javascript">
        function show(addr) {
            a = new XMLHttpRequest();
            a.onreadystatechange = function() {
                if (a.readyState==4 && a.status==200) {
                    document.getElementById("content").innerHTML=a.responseText;
                }
            }
            a.open("GET",addr+".php",true); 
            a.send(); //
        }
    </script>
</head>
<body>
    <a href="#" onClick="show('1')">Load 1.php into content</a>
    <a href="#" onClick="show('2')">Load 2.php into content</a>
    <a href="#" onClick="show('3')">Load 3.php into content</a>
    <a href="#" onClick="show('4')">Load 4.php into content</a>

    <!-- Load content here-->
    <div id="content"></div>        
</body>
</html>
</pre>
役に立ちましたか?

解決

アンカーが一意のタグ名を持っていても、ブラウザの履歴をナビゲートしてその特定のアンカーに戻ると、そのアンカーのオンクリックに関連付けられたJavaScriptを実行しません。

window.onhashchangeを設定して、ショー機能を呼び出す必要があります。変更後もオンクリックする必要さえありません。以下をテストしました:

    <pre>
    <html>
    <head>
        <script type="text/javascript">
            window.onhashchange=window.onload=function(){
                window.setTimeout(doHashCheck, 10);
            }

            var doHashCheck = (function(global) {
                return function() {
                    var addr = window.location.hash.replace(/^#/,'');
                    show(addr);
                }
            })(this);
            function show(addr)
            {
                a=new XMLHttpRequest();
                a.onreadystatechange=function()
                {
                    if (a.readyState==4 && a.status==200)
                    {
                        document.getElementById("content").innerHTML=a.responseText;
                    }
                }
                a.open("GET",addr+".php",true);
                a.send(); //
            }




        </script>

    <META HTTP-EQUIV="Pragma" CONTENT="no-cache" />
    <META HTTP-EQUIV="Expires" CONTENT="-1" />
    <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, no-store, must-revalidate" />

    </head>
    <a href="#1">Load 1.php into content</a>
    <a href="#2">Load 2.php into content</a>
    <a href="#3">Load 3.php into content</a>
    <a href="#4">Load 4.php into content</a>

    <!-- Load content here-->
    <div id="content"></div>
    </body>
    </html>
    </pre>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top