How can I trigger a function when the URL changes? I try something like:
$(windows.location).change(function(){
//execute code
});
So my URL is something like http://www.mysite.com/index.html#/page/1
. How can I execute jQuery or JavaScript code when the URL becomes something like http://www.mysite.com/index.html#/page/2
?
That would be a hashchange
event, so I'd suggest:
$(window).on('hashchange', function(e){
// do something...
});
References:
on()
. 尝试hashchange
事件,它正是为此而构建的 - http://benalman.com/projects/jquery-hashchange-plugin/
You could also try using http://www.asual.com/jquery/address/
$(function(){
$.address.strict(false);
$.address.internalChange(function(e) {
// do something here
});
});
var current_href = location.href;
setInterval(function(){
if(current_href !== location.href){
// if changed Do ...
current_href = location.href;
}else{
// Do ...
}
},500);
This worked for me ^^
$(window).on('hashchange') // not firing
To Detect URL change only for pop use
window.onpopstate = function (event) { // enter code here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.