Javascript 使用 jQuery 重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4611504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect Using jQuery
提问by tshauck
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.
所以我将 jquerymobile 用于我正在创建的应用程序。我有一个链接,如果所有验证都通过,我想通过,但如果出现问题,我想重定向。
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.
在 jquery 中是这样的。由于它是 jquerymobile,因此链接将是同一 index.html 页面上的新 div - 如果有帮助的话。
$(#link).click(function(){
if(validation_fails) link_elsewhere;
else return true;
}
采纳答案by Razor Storm
You can use the window.location to redirect a browser:
您可以使用 window.location 重定向浏览器:
回答by jondavidjohn
You can use JavaScript's nativewindow.location
您可以使用 JavaScript 的原生window.location
$('#link').click(function(){
if(validation_fails) {
window.location="http://this.site.com/";
}
else {
return true;
}
}
回答by Phrogz
$(#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.
您需要@Cybermate 答案之外的额外代码,否则每次失败时您都会继续附加哈希,例如“http://foo.com/bar#whee”,然后是“”http://foo.com/bar #whee#whee”等。
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";
回答by Chandu
You can hash the div id to the window.location to display the div. Something like:
您可以将 div id 散列到 window.location 以显示 div。就像是:
$(#link).click(function(){
if(validation_fails) window.location += "#<YOUR_DIV_ID>" ;
else return true;
}