如果函数与window.location.hash有帮助

5
我有一个函数,可以更改URL中的哈希值并插入/删除主页面中的div。我这样做是为了让用户在无需重新加载页面的情况下浏览页面,但同时也想让用户能够将某个特定部分加为书签,并在以后直接访问而无需再次浏览整个页面。
当我尝试调用我的hash()函数时,它不起作用。我可能在if语句中没有正确的内容,因为当我在hash()函数中放置一个alert()时,它会像预期的那样弹出。
function hash(){
    if ( window.location.hash == "dcontact" ) { 
        removedivs();
        InsertContent('dcontact');
    }
    if ( window.location.hash == "dhome" ) {
       removedivs();
       InsertContent('dhome');
    }
}
hash();

我知道可能有更好的方法来完成我提到的所有事情,但这是我唯一要做的网站,最终脚本多乱我都不在意,只要它能正常工作。

1个回答

7

无法正常工作的原因是window.location.hash开头的实际哈希符号(在美国我想你称之为“井号”)-#。

从记忆中看,IE不会将其放在哈希符号上,所以请这样做:

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

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

您可以考虑直接调用InsertContent(hash),而不是为每个不同的链接都做一个if()判断。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接