2010-11-18 49 views
5

我有一個函數可以改變URL中的哈希值,並在我的主頁面插入/刪除div。我這樣做是爲了讓我可以在沒有重新加載的情況下操作一個頁面,但是同時我希望人們能夠爲某個部分添加書籤並稍後再進行操作,而無需再次瀏覽該頁面。if function with window.location.hash help

當我嘗試打電話給我的hash()函數時,它會關閉所有div並根據散列打開特定的div,但它不起作用。我可能在if聲明中沒有正確的東西,因爲當我在hash()函數中插入alert()時,它會彈出它的設想。

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

我知道,這樣做有我提到的一切可能更好的方法,但是這是唯一的網站,我將要作出的,我一點也不在乎劇本如何凌亂是最後,只要它有效。

回答

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(散),而不是如果()爲每一個不同的鏈接做一個你必須

+0

非常感謝您幫助,它完美運作。 – pobrien 2010-11-18 21:44:53