您好,登錄后才能下訂單哦!
這篇文章主要用代碼詳解js實現(xiàn)無刷新監(jiān)聽URL的變化,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。
無刷新改變路由的兩種方法通過hash改變路由
代碼
window.location.hash='edit'
效果
http://xxxx/#edit
通過history改變路由
監(jiān)聽url變化
監(jiān)聽hash變化
window.onhashchange=function(event){ console.log(event); } //或者 window.addEventListener('hashchange',function(event){ console.log(event); })
監(jiān)聽back/forward/go
如果是history.back(),history.forward()、history.go()那么會觸發(fā)popstate事件
window.addEventListener('popstate', function(event) { console.log(event); })
但是,history.pushState()和history.replaceState()不會觸發(fā)popstate事件,所以需要自己手動增加事件
監(jiān)聽pushState/replaceState
history.replaceState和pushState不會觸發(fā)popstate事件,那么如何監(jiān)聽這兩個行為呢??梢酝ㄟ^在方法里面主動的去觸發(fā)popstate事件。另一種就是在方法中創(chuàng)建一個新的全局事件。
改造
const _historyWrap = function(type) { const orig = history[type]; const e = new Event(type); return function() { const rv = orig.apply(this, arguments); e.arguments = arguments; window.dispatchEvent(e); return rv; }; }; history.pushState = _historyWrap('pushState'); history.replaceState = _historyWrap('replaceState');
監(jiān)聽
window.addEventListener('pushState', function(e) { console.log('change pushState'); }); window.addEventListener('replaceState', function(e) { console.log('change replaceState'); });
看完上述內(nèi)容,是不是對用代碼詳解js實現(xiàn)無刷新監(jiān)聽URL的變化有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。