假設我有一個網頁index.html
。假設客戶去index.html#section2
。這應該將客戶端帶到具有名稱屬性爲section2
的塊級元素的頁面部分。如何使用javascript檢測內聯鏈接?
如何在javascript中檢測此內嵌鏈接?具體來說,如果用戶轉到index.html#section2
,我想在javascript中運行某個函數。
我很樂意使用jQuery。謝謝!
假設我有一個網頁index.html
。假設客戶去index.html#section2
。這應該將客戶端帶到具有名稱屬性爲section2
的塊級元素的頁面部分。如何使用javascript檢測內聯鏈接?
如何在javascript中檢測此內嵌鏈接?具體來說,如果用戶轉到index.html#section2
,我想在javascript中運行某個函數。
我很樂意使用jQuery。謝謝!
使用jQuery這個jQuery插件 http://benalman.com/projects/jquery-hashchange-plugin/
然後,你可以這樣做:
$(window).bind('hashchange', function(event) {
if(window.location.hash === "#section2"){
// What you want to do
}
})
或者如果你不想使用jQuery只是使用onclick事件。
<a href="#section2" onclick="changed()"></a>
JS:
function changed(){
setTimeout(function(){
if(window.location.hash === "#section2"){
// What you want to do
}
})
}
window.onload = changed; // In case user starts on #section2
謝謝!我喜歡jQuery解決方案。顯然,它沒有插件。嗯。 – dangerChihuahua007 2011-12-31 21:51:42
@ChiZeng該插件適用於不支持'window.hashchange'事件的瀏覽器。 – xandercoded 2011-12-31 21:53:15
不使用'hashchange'事件的缺點是,如果通過除點擊錨之外的其他方式來改變'hash',應用程序可以被拋出的狀態...... – xandercoded 2011-12-31 21:55:32
對window.location.hash
屬性執行switch
屬性。
switch(window.location.hash) {
case '#section1':
foo();
case '#section2':
bar();
}
注意 - 該hash
屬性在所有主流瀏覽器的支持。
編輯 - @IvanCastellanos是正確的關於新hashchange
事件和缺乏低級別的瀏覽器的支持。如果OP需要處理這種情況,則插件的開銷可能是必要的 - 在他的回答中指出...
哇,謝謝!我不知道這個屬性。 – dangerChihuahua007 2011-12-31 21:34:04
此解決方案僅在用戶在index.html#section2上啓動時纔有效,但如果用戶單擊頁面內部的鏈接則不起作用。 – 2011-12-31 21:37:57
具有'section2'的'id'屬性; 'name'已被棄用。 – Domenic 2011-12-31 21:39:07