229

How to go to a URL using jQuery or JavaScript.

<a href="javascript:void(0)"  onclick="javascript:goToURL()">Go To URL</a>

function goToURL(url){
// some code to go to url

}

I don't want to use window.location as I want to invoke this link from a popup.

New link should also open in a popup. I also don't want to use Ajax. Just simulate href in JavaScript.

4

4 回答 4

383
//As an HTTP redirect (back button will not work )
window.location.replace("http://www.google.com");

//like if you click on a link (it will be saved in the session history, 
//so the back button will work as expected)
window.location.href = "http://www.google.com";
于 2013-06-06T10:23:51.807 回答
107

为什么不使用?

location.href='http://www.example.com';

<!DOCTYPE html>
<html>

<head>
  <script>
    function goToURL() {
      location.href = 'http://google.it';

    }
  </script>
</head>

<body>
  <a href="javascript:void(0)" onclick="goToURL(); return false;">Go To URL</a>
</body>

</html>

于 2013-06-06T10:22:07.840 回答
21

window.location 正是您所需要的。您可以做的其他事情是创建锚元素并模拟点击它

$("<a href='your url'></a>").click(); 
于 2013-06-06T10:18:29.353 回答
3

实际上,你必须使用锚 # 来玩这个。如果您对 Gmail 网址系统进行逆向工程,您会发现

https://mail.google.com/mail/u/0/#inbox
https://mail.google.com/mail/u/0/#inbox?compose=new

# 之后的所有内容都是您要在页面中加载的部分,然后您只需选择加载位置即可。

顺便说一句,通过添加 #something 来使用 document.location 不会刷新您的页面。

于 2013-06-06T10:22:15.123 回答