Redirect Using jQuery [duplicate]
So I'm using jquerymobile开发者_开发百科 for an app I'm creating. I have a link that if all the validation passes I'd like to go through, but if something fails I'd like to redirect.
In the jquery something like this. Since it is jquerymobile the link will be a new div on the same index.html page - if that helps.
$(#link).click(function(){
if(validation_fails) link_elsewhere;
else return true;
}
You can use the window.location to redirect a browser:
https://developer.mozilla.org/en/DOM/window.location
You can use JavaScript's native window.location
$('#link').click(function(){
if(validation_fails) {
window.location="http://this.site.com/";
}
else {
return true;
}
}
You can hash the div id to the window.location to display the div. Something like:
$(#link).click(function(){
if(validation_fails) window.location += "#<YOUR_DIV_ID>" ;
else return true;
}
$(#link).click(function(){
if(validation_fails){
var loc = window.location;
window.location = loc.protocol+"//"+loc.hostname+loc.pathname+"#somedivid";
} else return true;
}
You need the extra code beyond @Cybermate's answer because otherwise you'll keep appending the hash each time it fails, e.g. "http://foo.com/bar#whee", then ""http://foo.com/bar#whee#whee", etc.
Edit: If the port might be used, you can conditionally include it:
window.location = loc.protocol + "//" + loc.hostname +
(loc.port && ":"+loc.port) +
loc.pathname + "#somedivid";
精彩评论