2012-04-10 20 views
0

嗨我有一個頁面,使用錨點進行導航。加載時,索引頁面(A)需要跳轉到錨點。很好,我可以在加載函數中做到這一點,但從頁面B回到頁面A我想跳轉到不同的錨點。我有這樣的工作:去負載錨點(如果其他語句)

<!-- go to Anchor --> 
    <script type="text/javascript"> 

    function goToAnchor() { 
    var urllocation = location.href; 
    if(urllocation.indexOf("#top") > -1){ 
     window.location.hash="top"; 
    } else { 
    window.location.hash="middle"; 
    } 
} 
    </script> 

#middle是不包含錨鏈接來(或鍵入地址到地址欄)時使用的錨。我想添加三個'如果'。如果我正在做一些愚蠢的事情,我對js很新,所以對我很感興趣。我試過這個:

function goToAnchor() { 
    var urllocation = location.href;   
if(urllocation.indexOf("#right") > -1){ 
     window.location.hash="right"; 
    } else { 
    window.location.hash="middle"; 
    } 
    if(urllocation.indexOf("#bottom") > -1){ 
     window.location.hash="bottom"; 
    } else { 
    window.location.hash="middle"; 
    } 
    if(urllocation.indexOf("#left") > -1){ 
     window.location.hash="left"; 
    } else { 
    window.location.hash="middle"; 
    } 

但不是快樂,js打破了,不再去頁面加載#middle。

我嘗試了外卡的方法:

function goToAnchor() { 
var urllocation = location.href; 
if(urllocation.indexOf("#.") > -1){ 
    window.location.hash="."; 
} else { 
window.location.hash="middle"; 
} 

}

同樣,沒有喜悅。

任何幫助,請..謝謝好心

回答

1

我不太明白你正在努力實現(因爲window.location.hash應該包含您的網址的散列部),但你的代碼也許應該寧可

function goToAnchor() { 
    var urllocation = location.href;   
    if (urllocation.indexOf("#right") > -1) { 
     window.location.hash = "right"; 
    } else if (urllocation.indexOf("#bottom") > -1) { 
     window.location.hash = "bottom"; 
    } else if(urllocation.indexOf("#left") > -1) { 
     window.location.hash = "left"; 
    } else { 
     window.location.hash = "middle"; 
    } 
} 

我的影響我還猜測你的「外卡」的方式是指使用正則表達式:

function goToAnchor() { 
    var urllocation = location.href; 
    var hashMatch = urllocation.match(/#(.*)/) 
    if (hashMatch){ 
     window.location.hash = hashMatch[1]; 
    } else { 
     window.location.hash = "middle"; 
    } 
} 

再次,我不太看到這個代碼應該有什麼樣的影響,因爲window.location.hash在分配前後可能具有相同的值。

+0

@朱利安D. 完美的,通配符的方法,因爲我想要的。我知道這很簡單,我正在聚集。至於如果其他方法,我從來沒有想過這個... 感謝所有的快速答覆。 – vincentieo 2012-04-10 16:55:36

1

如果你只是想回去散列在URL中,你有沒有嘗試過這樣的事情?

var hash = window.location.hash || "middle"; //Get current hash or default to "middle" if no hash is currently set 
window.location.hash = +new Date() + ""; //Remove the hash and set it to some random value 
window.location.hash = hash; //Set to the old hash 
+0

是'= + new Date()'我不知道的一個語法,還是一個錯誤? – jbabey 2012-04-10 14:37:47

+0

'+'操作符基本上是指「將其轉換爲整數」,它將日期對象轉換爲數字時間戳。 – apsillers 2012-04-10 14:41:41

+0

@ jbabey像apsillers說的那樣,它有點魔法。它在對象上調用'.valueOf'並添加另一個操作數(在這種情況下爲0,因爲我沒有在'+'之前放置任何東西)。這可以重寫爲new Date()。valueOf()。toString()'。 – 2012-04-10 14:48:13