使用 jQuery 更改 URL 和重定向 [英] Change URL and redirect using jQuery

查看:66
本文介绍了使用 jQuery 更改 URL 和重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的代码,

<form id="abc">
  <input type="text" id="txt" />
</form>

现在我想像这样重定向,

and now I want to redirect like this,

var temp = $("#txt").val();
url = "http://example.com/" + temp;
window.location.replace(url);
// or window.location(url);

无论如何在jQuery中可以解决这个问题吗?它仍然让我拥有 url = http://example.com.

Is there anyway in jQuery to solve this? It still lets me have url = http://example.com.

推荐答案

正如其他答案中提到的,您不需要 jQuery 来执行此操作;您可以只使用标准属性.

As mentioned in the other answers, you don't need jQuery to do this; you can just use the standard properties.

但是,您似乎不知道 window.location.replace(url)window.location = url 之间的区别.

However, it seems you don't seem to know the difference between window.location.replace(url) and window.location = url.

  1. window.location.replace(url) 将地址栏中的当前位置替换为一个新位置.调用该函数的页面不会包含在浏览器历史记录中.因此,在新位置,单击浏览器中的后退按钮将使您返回到访问包含重定向 JavaScript 的文档之前正在查看的页面.
  2. window.location = url 重定向到新位置.在这个新页面上,浏览器中的后退按钮将指向包含重定向 JavaScript 的原始页面.
  1. window.location.replace(url) replaces the current location in the address bar by a new one. The page that was calling the function, won't be included in the browser history. Therefore, on the new location, clicking the back button in your browser would make you go back to the page you were viewing before you visited the document containing the redirecting JavaScript.
  2. window.location = url redirects to the new location. On this new page, the back button in your browser would point to the original page containing the redirecting JavaScript.

当然,两者都有其用例,但在我看来,在这种情况下,您应该坚持使用后者.

Of course, both have their use cases, but it seems to me like in this case you should stick with the latter.

P.S.:您可能忘记了 JavaScript 第 2 行 http: 后面的两个斜杠:

P.S.: You probably forgot two slashes after http: on line 2 of your JavaScript:

url = "http://abc.com/" + temp;

这篇关于使用 jQuery 更改 URL 和重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆