假设:我单击1.php,然后2.php然后3.php,然后按回去,但不会转到2.php也没有影响URL。我也想更改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。

您需要设置窗口。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