开发者

if function with window.location.hash help

开发者 https://www.devze.com 2023-01-25 22:10 出处:网络
I have a function that changes the hash in the url and inserts/removes a div from my main page. I did this was so that I can have a page that you can maneuver through without a reload, but at the same

I have a function that changes the hash in the url and inserts/removes a div from my main page. I did this was so that I can have a page that you can maneuver through without a reload, but at the same time i wanted people to be able to bookmark a certain section and go to it later without having to go through the page again.

When i try to call my hash() function, which closes all divs and opens up the specific div depending on the hash, it doesn't work. I probably dont have the right thing in the if statements, because when I put an alert() in the hash() function, it pops up like its supposed to.

function hash(){
    if ( window.location.hash == "dcontact" ) { 
        removedivs();
        InsertContent('dcontact');
    }
    if ( window.location.hash == "dhome" ) {
       removedivs();
       InsertContent('dhome');
    }
}
hash();

I'm aware that there are probably better ways of doing everything i mentioned, but this is the only website I'm going to be makin开发者_Python百科g, and I couldn't care less how messy the script is in the end, as long as it works.


the reason it doesn't work is the actual hash (in the US I think you call it a pound) symbol - # at the beginning of window.location.hash

From memory IE doesn't put the hash symbol on it, so do this:

function hash() {
    var hash = window.location.hash.replace('#','');

    if (hash == "dcontact"){removedivs(); InsertContent('dcontact');}
    if (hash == "dhome"){removedivs(); InsertContent('dhome');}  
}

You could also consider just calling InsertContent(hash) rather than doing an if() for every different link you'll have

0

精彩评论

暂无评论...
验证码 换一张
取 消