开发者

Redirect Using jQuery [duplicate]

This question already has answers here: How do I redirect to another webpage? (58 answers) Closed 6 years ago.

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";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜