How to get/set current page URL (which works across space-time-browsers-versions)

自古美人都是妖i 提交于 2020-03-18 10:25:14

问题


I want to get/set URL of the current page upon certain event.

It seems there are more than one approach for doing it as mentioned in questions/answers below.

Using Jquery

Get URL - $(location).attr('href');
Set URL - $(location).attr('href',url);

Using JavaScript

Get URL - myVar = window.location.href;
Set URL - window.location.href = "http://stackoverflow.com";

Which approach works across space-time-browsers-versions?

Get current URL in JavaScript?

How to redirect to another webpage in JavaScript/jQuery?


回答1:


I don't see any need to use jQuery for this. The following will work perfectly fine in all browsers:

window.location.href = "http://stackoverflow.com";

Or even more simply:

location.href = "http://stackoverflow.com";



回答2:


I agree with @meub . this will also do :

window.location.replace("http://stackoverflow.com");

To behave as clicking a link you need to use simple javascript . You don't need jQuery for doing that. You can use the following:

Get URL - myVar = window.location.href;
SET URL - window.location.href = "http://stackoverflow.com";


来源:https://stackoverflow.com/questions/18396501/how-to-get-set-current-page-url-which-works-across-space-time-browsers-versions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!