Jquery链接和URL哈希

时间:2014-02-09 23:53:00

标签: javascript php jquery html

我是jQuery的新手,并不知道我在做什么。我需要一些帮助。

我正在创建一个网络应用。它有一个页眉和页脚,我想留在每个页面,所以我决定使用jQuery将页面加载到主内容div中,所以每次点击一个链接,整个页面都不会重新加载。

以下是我用来完成此任务的内容:

<script>
    $(function() {
        $("a.ajax-link").on("click", function(e) {
            e.preventDefault();
            $("#main_content").fadeOut('fast');
            $("#main_content").load(this.href);
            $('html, body').animate({ scrollTop: 0 }, 0);
            $("#main_content").fadeIn('fast');
        });
    });
  </script>

每个链接:

<a class="ajax-link" id="add" href="add.php"><span class="glyphicon glyphicon-plus-sign" style="margin-top:4px;"></span><div>add</div></a>

除了页面地址外,它的效果很好。我的应用程序使用PHP,我需要能够将PHP Header转换为像'index.php#about'这样的页面,它将加载index.php页面并在#main_content div中显示about.php。

我试过了:

<script type="text/javascript">
    $(document).ready(function(){
       var id = window.location.hash;
       $(id).trigger('click');
    })
  </script>

我可以看到链接的选择位置(它周围的框),但实际上并没有点击它。我不确定为什么。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为你可以获得哈希,添加一个php扩展并进行ajax调用。

<script>
    $(function() {
        $("a.ajax-link").on("click", function(e) {
            e.preventDefault();

            // Get the hash from the URL and append .php extension
            // index.php#about ==> 'about.php'

            var page = window.location.hash + ".php";

            //Make an ajax call using the page variable.

            $("#main_content").fadeOut('fast');
            $("#main_content").load(page);
            $('html, body').animate({ scrollTop: 0 }, 0);
            $("#main_content").fadeIn('fast');
        });
    });
</script>