如何将函数绑定到 URL 查询字符串的更改,而不是 hashchange [英] How to bind a function to change of URL query string, NOT to hashchange
问题描述
正如标题所暗示的,我希望将一个函数绑定到 URL 查询字符串的更改.
As the title suggests, I'm looking to bind a function to the change of the URL query string.
示例:
来自: /baby
至: /baby/?_bc_fsnf=1&brand[]=37
详细地说,我希望函数在 from 变成 to 时运行.
To elaborate, I'd want the function to run when the from turns into the to.
干杯!
推荐答案
如果你的页面没有刷新,可能是有人调用了 history.pushState
或 history.replaceState
更改网址.
If your page is not refreshing, someone is probably calling history.pushState
or history.replaceState
to change the URL.
有内置的方法来跟踪 pushState
和 replaceState
何时被调用,但是您可以通过使用此 track包装每个函数来自己跟踪它们代码> 实用程序:
There is built-in way to track when pushState
and replaceState
are called, but you can track them yourself by wrapping each function using this track
utility:
function track (fn, handler, before) {
return function interceptor () {
if (before) {
handler.apply(this, arguments)
return fn.apply(this, arguments)
} else {
var result = fn.apply(this, arguments)
handler.apply(this, arguments)
return result
}
}
}
var oldQs = location.search
function handler () {
console.log('Query-string changed:',
oldQs || '(empty)', '=>',
location.search || '(empty)'
)
oldQs = location.search
}
// Assign listeners
history.pushState = track(history.pushState, handler)
history.replaceState = track(history.replaceState, handler)
window.addEventListener('popstate', handler)
// Example code to change the URL
history.pushState(null, 'Title 1', '/baby/?key=value')
history.replaceState(null, 'Title 2', '/baby/?_bc_fsnf=1&brand[]=37')
这篇关于如何将函数绑定到 URL 查询字符串的更改,而不是 hashchange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!