對URL hash的操作

來源:互聯網
上載者:User

標籤:

一、什麼是hash?如何擷取hash?

   hash 是 HTML DOM location 對象的一個屬性,它是儲存 URL 錨部分(從 # 號開始的部分)的一個字串。hash的變化不會引起瀏覽器的重新重新整理,具體擷取hash的代碼如下:

var hash = window.location.hash;

 需要注意的是firefox會對location.hash擷取的字串進行解碼,如果有相關操作請使用以下代碼:

var url = window.location.href;var index = url.indexOf(‘#‘);var hash = index == -1 ? ‘‘ : url.slice(index);return hash;

 

二、監聽hash執行相應邏輯

 javascript提供了事件hashchange來進行對hash的監聽,該事件對象下有兩個屬性:oldURL與newURL。應該注意的是該事件只相容IE8+的IE瀏覽器,所以下面我們使用指令碼類比該事件,在window.onhashchange上綁定事件處理函數。

(function(window) {    
// 自執行匿名函數 // 如果瀏覽器原生支援該事件,則退出 if ( "onhashchange" in window.document.body ) { return; } var location = window.location, oldURL = location.href, oldHash = location.hash; // 每隔100ms檢測一下location.hash是否發生變化 setInterval(function() { var newURL = location.href, newHash = location.hash; // 如果hash發生了變化,且綁定了處理函數... if ( newHash != oldHash && typeof window.onhashchange === "function" ) { // execute the handler window.onhashchange({ type: "hashchange", oldURL: oldURL, newURL: newURL }); oldURL = newURL; oldHash = newHash; } }, 100);})(window);

 

對URL hash的操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.