对于加载了ajax的内容,window.location.hash是未定义的

时间:2012-11-06 09:59:36

标签: javascript jquery ajax

我正在wordpress单页网站上用ajax加载内容。我试图在每次加载ajax帖子时更改url。

这是我用来在单击项目时修改哈希的代码。加载函数正在运行,因此我不会为了清晰起见将其添加到下面的代码中(它只需要点击li的href并将内容加载到div中)。

    $(document).ready(function() {
        $.ajaxSetup({cache: false});

        $('#portfolio-list li:not(#DrawerContainer)').click(function() {

           window.location.hash = "#!" + this.pathname;
           alert(window.location.hash);

        //And here comes the loading part

        return false;
        });

    return false;       
    });

不幸的是,添加到我的网址的唯一内容是#!undefined。警告window.location.hashthis.pathname会给我相同的结果。

我需要在地址栏中将路径名作为哈希返回?

1 个答案:

答案 0 :(得分:0)

根据你的结构,这应该是你友好的哈希:

var pathname = $(this).find('a')[0].href.split('/'),
    l = pathname.length;
pathname = pathname[l-1] || pathname[l-2];
window.location.hash = "#!" + pathname;

Demo

<小时/> 现在要使URL可共享,您需要对DOM准备好哈希检查并加载相应的内容。

如果所有页面都在同一目录中,您可以直接进行:

 $(function() {
     var hash = window.location.hash;
     //checks if hash exists and is hash bang
     if (hash && hash.substring(0, 2) === '#!') {
         hash = hash.substring(2); //removes leading #!
         $('#content').load('path/to/' + hash);
     }
 });

Demo

如果页面不在同一目录中,则需要将哈希值映射到地址。

$(function() {
    var hashmap = {
        'test5': 'http://foobar.baz/fooz/test5',
        'anotherTest': 'http://foobar.baz/barz/anotherTest',
    };
    var hash = window.location.hash;
    //checks if hash exists and is hash bang
    if (hash && hash.substring(0, 2) === '#!') {
        hash = hash.substring(2); //removes leading #!
        if (hashmap[hash]) { //checks if hash exist in the hash map
            $('#content').load(hashmap[hash]);
        }
    }
});

Demo

我在上面的演示中使用警报,因为加载会失败。当然,您必须通过首选加载方法来调整/替换$('#content').load

相关问题