1

我的脚本在这里有一点问题。出于某种原因,它没有启用#-tags,我不知道为什么。我在本教程的帮助下创建了这个 javascript 。(页面加载运行良好,完全没有问题。)

有人可以看看它并告诉我为什么它不起作用吗?

 var default_content="";

    $(document).ready(function(){   //executed after the page has loaded

        checkURL(); //check if the URL has a reference to a page and load it

        $('ul li a').click(function (e){    //traverse through all our navigation links..

                checkURL(this.hash);    //.. and assign them a new onclick event, using their own hash as a parameter (#page1 for example)

        });

        setInterval("checkURL()",250);  //check for a change in the URL every 250 ms to detect if the history buttons have been used

    });

    var lasturl=""; //here we store the current URL hash

    function checkURL(hash)
    {
        if(!hash) hash=window.location.hash;    //if no parameter is provided, use the hash value from the current address

        if(hash != lasturl) // if the hash value has changed
        {
            lasturl=hash;   //update the current hash
            loadPage(hash); // and load the new page
        }
    }

    function loadPage(url)  //the function that loads pages via AJAX
    {
        // Instead of stripping off #page, only 
        // strip off the # to use the rest of the URL
        url=url.replace('#','');

     $('#loading').css('visibility','visible'); //show the rotating gif animation

         $.ajax({
            type: "POST",
            url: "load_page.php",
            data: 'page='+url,
            dataType: "html",
            success: function(msg){

                   if(parseInt(msg)!=0) //if no errors
                {
                    $('#content').html(msg);    //load the returned html into pageContet

                }  $('#loading').css('visibility','hidden');//and hide the rotating gif
            }

        });

    }
4

1 回答 1

1

您可以通过添加一个监听hashchange事件的函数来极大地简化这一点,如下所示:

$(window).on("hashchange", function() {
    loadPage(window.location.hash);
});

这样您就不需要处理计时器或覆盖锚点上的点击事件。

您也不需要跟踪,lasthash因为hashchangeeven 只会在哈希更改时触发。

于 2013-08-20T19:31:59.867 回答