jQuery特定内容加载不使用#links

时间:2013-02-25 20:21:08

标签: jquery html

这是我的代码:

http://jsfiddle.net/h3ctt/

如果您在未加载页面的情况下导航至www.example.com/page.html#example-name1,则会显示整个页面而不是请求的内容。

但是,如果您在页面加载后导航到链接,它将工作并显示所需的内容。

这很奇怪。有没有人解决这个问题?

2 个答案:

答案 0 :(得分:1)

您应该检查哈希onloadonhashchange

// On page load
$(document).ready(function(){
    // When the hash (#something) changes
    window.onhashchange = function() {
        doAction();
    };

    doAction();

    function doAction() {
        // get the current hash minus '#'
        var profileId = window.location.hash.substr(1);

        if(profileId != '') {
            // hide all profiles
            $('.profile').hide();
            // show only the appropriate profile
            $('#' + profileId).show();
        }
    }
});

答案 1 :(得分:0)

我相对确定您无法在jsfiddle 上显示该功能,但是,如果您位于正确的页面上,则网址中的page.html#example-name1 bar应该会产生您想要显示的功能。然而,为了使它在适当的页面上工作,你必须做你的代码所建议的aboodred1,即在hashchange上运行代码。这是为了确保在更改网址时,它会显示该特定内容。