欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何重定向到另一个网页?

程序员文章站 2022-05-22 23:33:52
...
英文原文地址为:How do I redirect to another webpage?

How can I redirect the user from one page to another using jQuery or pure JavaScript?

如何使用jQuery或纯JavaScript将用户从一个页面重定向到另一个页面?

30 个解决方案

#1


12438  

One does not simply redirect using jQuery

jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.

jQuery并不是必需的,而window.location.replace(…)将最好地模拟一个HTTP重定向。

window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

替换(…)比使用window.location更好。href,因为replace()没有保留会话历史中的原始页面,这意味着用户不会陷入无休止的后退按钮失败。

If you want to simulate someone clicking on a link, use location.href

如果您想模拟某人点击一个链接,请使用location.href。

If you want to simulate an HTTP redirect, use location.replace

如果您想模拟HTTP重定向,请使用位置。replace。

For example:

例如:

// similar behavior as an HTTP redirect
window.location.replace("http://*.com");

// similar behavior as clicking on a link
window.location.href = "http://*.com";

#2


1392  

WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.

警告:这个答案只是作为一种可能的解决方案提供的;这显然不是最好的解决方案,因为它需要jQuery。相反,更喜欢纯JavaScript解决方案。

$(location).attr('href', 'http://*.com')

#3


470  

Standard "vanilla" JavaScript way to redirect a page:

标准的“香草”JavaScript方法重定向页面:

window.location.href = 'newPage.html';

window.location。href = ' newPage.html ';


If you are here because you are losing HTTP_REFERER when redirecting, keep reading:

如果您在这里,因为您在重定向时丢失了HTTP_REFERER,请继续阅读:


The following section is for those using HTTP_REFERER as one of many secure measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).

下面的部分是使用HTTP_REFERER作为许多安全措施之一(尽管它不是一个很好的保护措施)。如果您使用的是Internet Explorer 8或更低,那么在使用任何形式的JavaScript页面重定向(位置)时,这些变量都会丢失。href,等等)。

Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise you can almost always simply use window.location.href.

下面我们将实现IE8 & lower的一个替代方案,这样我们就不会失去HTTP_REFERER。否则,您几乎可以只使用window.location.href。

Testing against HTTP_REFERER (URL pasting, session, etc.) can be helpful in telling whether a request is legitimate. (Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)

对HTTP_REFERER (URL粘贴、会话等)进行测试有助于判断请求是否合法。(注意:也有一些方法可以对这些引用进行工作/欺骗,如droop在评论中的链接所指出的那样)


Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)

简单的跨浏览器测试解决方案(返回到windows .location。href为Internet Explorer 9+和所有其他浏览器)

Usage: redirect('anotherpage.aspx');

用法:重定向(“anotherpage.aspx”);

function redirect (url) {
    var ua        = navigator.userAgent.toLowerCase(),
        isIE      = ua.indexOf('msie') !== -1,
        version   = parseInt(ua.substr(4, 2), 10);

    // Internet Explorer 8 and lower
    if (isIE && version < 9) {
        var link = document.createElement('a');
        link.href = url;
        document.body.appendChild(link);
        link.click();
    }

    // All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
    else { 
        window.location.href = url; 
    }
}

#4


326  

Use:

使用:

// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'

// window.history
window.history.back()
window.history.go(-1)

// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')


// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';

// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')

#5


249  

This works for every browser:

这适用于每一个浏览器:

window.location.href = 'your_url';

#6


236  

It would help if you were a little more descriptive in what you are trying to do. If you are trying to generate paged data, there are some options in how you do this. You can generate separate links for each page that you want to be able to get directly to.

如果你对自己想要做的事情有一点描述性的话会有所帮助。如果您正在尝试生成分页数据,那么在如何实现这一点上有一些选项。您可以为希望能够直接访问的每个页面生成单独的链接。

<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...

Note that the current page in the example is handled differently in the code and with CSS.

注意,示例中的当前页面在代码和CSS中处理方式不同。

If you want the paged data to be changed via AJAX, this is where jQuery would come in. What you would do is add a click handler to each of the anchor tags corresponding to a different page. This click handler would invoke some jQuery code that goes and fetches the next page via AJAX and updates the table with the new data. The example below assumes that you have a web service that returns the new page data.

如果您希望通过AJAX更改分页数据,那么这就是jQuery的切入点。您要做的是向每个与不同页面对应的锚标记添加一个单击处理程序。这个单击处理程序将调用一些jQuery代码,并通过AJAX获取下一个页面,并使用新数据更新表。下面的示例假设您有一个返回新页面数据的web服务。

$(document).ready( function() {
    $('a.pager-link').click( function() {
        var page = $(this).attr('href').split(/\?/)[1];
        $.ajax({
            type: 'POST',
            url: '/path-to-service',
            data: page,
            success: function(content) {
               $('#myTable').html(content);  // replace
            }
        });
        return false; // to stop link
    });
});

#7


193  

I also think that location.replace(URL) is the best way, but if you want to notify the search engines about your redirection (they don't analyze JavaScript code to see the redirection) you should add the rel="canonical" meta tag to your website.

我也认为位置。replace(URL)是最好的方法,但是如果你想要通知搜索引擎你的重定向(他们没有分析JavaScript代码来查看重定向),你应该在你的网站上添加rel="canonical" meta标签。

Adding a noscript section with a HTML refresh meta tag in it, is also a good solution. I suggest you to use this JavaScript redirection tool to create redirections. It also has Internet Explorer support to pass the HTTP referrer.

添加一个带有HTML刷新元标签的noscript部分也是一个很好的解决方案。我建议您使用这个JavaScript重定向工具来创建重定向。它也有Internet Explorer支持通过HTTP referrer。

Sample code without delay looks like this:

没有延迟的示例代码如下所示:

<!-- Place this snippet right after opening the head tag to make it work properly -->

<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->

<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.com/"/>
<noscript>
    <meta http-equiv="refresh" content="0;URL=https://yourdomain.com/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
    var url = "https://yourdomain.com/";
    if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
    {
        document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
        var referLink = document.createElement("a");
        referLink.href = url;
        document.body.appendChild(referLink);
        referLink.click();
    }
    else { window.location.replace(url); } // All other browsers
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->

#8


173  

But if someone wants to redirect back to home page then he may use the following snippet.

但是如果有人想重定向回主页,那么他可能会使用以下代码片段。

window.location = window.location.host

It would be helpful if you have three different environments as development, staging, and production.

如果您有三个不同的环境作为开发、登台和生产,将会很有帮助。

You can explore this window or window.location object by just putting these words in Chrome Console or Firebug's Console.

您可以探索这个窗口或窗口。通过将这些单词放入Chrome控制台或Firebug的控制台,就可以定位对象。

#9


163  

JavaScript provides you many methods to retrieve and change the current URL which is displayed in browser's address bar. All these methods uses the Location object, which is a property of the Window object. You can create a new Location object that has the current URL as follows..

JavaScript提供了许多方法来检索和更改显示在浏览器地址栏中的当前URL。所有这些方法都使用Location对象,这是窗口对象的属性。您可以创建一个新的Location对象,该对象具有如下所示的当前URL。

var currentLocation = window.location;

Basic Structure of a URL

URL的基本结构。

<protocol>//<hostname>:<port>/<pathname><search><hash>

如何重定向到另一个网页?

  1. Protocol -- Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))

    协议——指定用于在Internet*问资源的协议名称。(HTTP(无SSL)或HTTPS(使用SSL))

  2. hostname -- Host name specifies the host that owns the resource. For example, www.*.com. A server provides services using the name of the host.

    主机名——主机名指定拥有资源的主机。例如,www.*.com。服务器使用主机名提供服务。

  3. port -- A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.

    端口——用于识别一个特定进程的端口号,当它到达一个服务器时,一个Internet或其他网络消息将被转发。

  4. pathname -- The path gives info about the specific resource within the host that the Web client wants to access. For example, *.com/index.html.

    路径名——路径给出了Web客户机想要访问的主机中特定资源的信息。例如,*.com/index.html。

  5. query -- A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).

    查询——查询字符串遵循路径组件,并提供了资源可以用于某些用途的一系列信息(例如,作为搜索的参数或要处理的数据)。

  6. hash -- The anchor portion of a URL, includes the hash sign (#).

    哈希——URL的锚部分,包括哈希符号(#)。

With these Location object properties you can access all of these URL components

通过这些位置对象属性,您可以访问所有这些URL组件。

  1. hash -Sets or returns the anchor portion of a URL.
  2. 散列集或返回URL的锚部分。
  3. host -Sets or returns the hostname and port of a URL.
  4. 主机-设置或返回一个URL的主机名和端口。
  5. hostname -Sets or returns the hostname of a URL.
  6. 主机名-设置或返回一个URL的主机名。
  7. href -Sets or returns the entire URL.
  8. href -设置或返回整个URL。
  9. pathname -Sets or returns the path name of a URL.
  10. 路径名-设置或返回URL的路径名。
  11. port -Sets or returns the port number the server uses for a URL.
  12. 端口-设置或返回服务器用于URL的端口号。
  13. protocol -Sets or returns the protocol of a URL.
  14. 协议集或返回一个URL的协议。
  15. search -Sets or returns the query portion of a URL
  16. 搜索-设置或返回一个URL的查询部分。

Now If you want to change a page or redirect the user to some other page you can use the href property of the Location object like this

现在,如果您想要更改页面或将用户重定向到其他页面,您可以使用这样的位置对象的href属性。

You can use the href property of the Location object.

您可以使用Location对象的href属性。

window.location.href = "http://www.*.com";

Location Object also have these three methods

Location对象也有这三种方法。

  1. assign() -- Loads a new document.
  2. 分配()——加载一个新文档。
  3. reload() -- Reloads the current document.
  4. 重载()——重新加载当前文档。
  5. replace() -- Replaces the current document with a new one
  6. replace()——用一个新文档替换当前文档。

You can use assign() and replace methods also to redirect to other pages like these

您可以使用assign()和replace方法来重定向到其他类似的页面。

location.assign("http://www.*.com");

location.replace("http://www.*.com");

How assign() and replace() differs -- The difference between replace() method and assign() method(), is that replace() removes the URL of the current document from the document history, means it is not possible to use the "back" button to navigate back to the original document. So Use the assign() method if you want to load a new document, andwant to give the option to navigate back to the original document.

如何分配()和replace()不同——replace()方法和assign()方法之间的区别是,replace()将从文档历史中删除当前文档的URL,这意味着不可能使用“back”按钮返回原始文档。因此,如果您想要加载新文档,请使用assign()方法,并希望提供返回原始文档的选项。

You can change the location object href property using jQuery also like this

您可以使用jQuery更改位置对象href属性。

$(location).attr('href',url);

And hence you can redirect the user to some other url.

因此,您可以将用户重定向到其他url。

#10


146  

Should just be able to set using window.location.

应该能够使用window.location来设置。

Example:

例子:

window.location = "https://*.com/";

Here is a past post on the subject:

这里有一篇关于这个主题的文章:

How do I redirect to another webpage?

如何重定向到另一个网页?

#11


130  

Before I start, jQuery is a JavaScript library used for DOM manipulation. So you should not be using jQuery for a page redirect.

在开始之前,jQuery是一个用于DOM操作的JavaScript库。因此,您不应该使用jQuery进行页面重定向。

A quote from Jquery.com:

引用Jquery.com

While jQuery might run without major issues in older browser versions, we do not actively test jQuery in them and generally do not fix bugs that may appear in them.

虽然jQuery在旧的浏览器版本中可能没有重大问题,但我们并不积极地测试jQuery,通常也不会修复出现在它们中的错误。

It was found here: https://jquery.com/browser-support/

它是在这里找到的:https://jquery.com/browser-support/。

So jQuery is not an end-all and be-all solution for backwards compatibility.

因此,jQuery并不是向后兼容的最终解决方案。

The following solution using raw JavaScript works in all browsers and have been standard for a long time so you don't need any libraries for cross browser support.

下面的解决方案在所有的浏览器中使用原始的JavaScript,并且在很长一段时间内都是标准的,所以您不需要任何用于跨浏览器支持的库。

This page will redirect to Google after 3000 milliseconds

此页面将在3000毫秒后重定向到谷歌。

<!DOCTYPE html>
<html>
    <head>
        <title>example</title>
    </head>
    <body>
        <p>You will be redirected to google shortly.</p>
        <script>
            setTimeout(function(){
                window.location.href="http://www.google.com"; // The URL that will be redirected too.
            }, 3000); // The bigger the number the longer the delay.
        </script>
    </body>
</html>

Different options are as follows:

不同的选择如下:

window.location.href="url"; // Simulates normal navigation to a new page
window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL

window.history.back(); // Simulates a back button click
window.history.go(-1); // Simulates a back button click
window.history.back(-1); // Simulates a back button click
window.navigate("page.html"); // Same as window.location="url"

When using replace, the back button will not go back to the redirect page, as if it was never in the history. If you want the user to be able to go back to the redirect page then use window.location.href or window.location.assign. If you do use an option that lets the user go back to the redirect page, remember that when you enter the redirect page it will redirect you back. So put that into consideration when picking an option for your redirect. Under conditions where the page is only redirecting when an action is done by the user then having the page in the back button history will be okay. But if the page auto redirects then you should use replace so that the user can use the back button without getting forced back to the page the redirect sends.

当使用replace时,后退按钮不会返回到重定向页面,就好像它从来没有出现在历史中一样。如果您希望用户能够返回到重定向页面,那么可以使用window.location。href或window.location.assign。如果您使用一个选项,让用户返回到重定向页面,请记住,当您输入重定向页面时,它将重定向您。所以在选择重定向的选项时要考虑到这一点。在页面仅重定向的情况下,当用户执行操作时,在后退按钮历史上的页面将会是正常的。但是如果页面自动重定向,那么您应该使用replace,这样用户就可以使用back按钮,而不必*返回到重定向发送的页面。

You can also use meta data to run a page redirect as followed.

您还可以使用元数据来运行页面重定向,如下所示。

META Refresh

META刷新

<meta http-equiv="refresh" content="0;url=http://evil.com/" />

META Location

元的位置

<meta http-equiv="location" content="URL=http://evil.com" />

BASE Hijacking

基地劫持

<base href="http://evil.com/" />

Many more methods to redirect your unsuspecting client to a page they may not wish to go can be found on this page (not one of them is reliant on jQuery):

在这个页面上可以找到更多的方法来重定向你毫无疑心的客户端到他们可能不想去的页面(而不是依赖jQuery):

https://code.google.com/p/html5security/wiki/RedirectionMethods

https://code.google.com/p/html5security/wiki/RedirectionMethods

I would also like to point out, people don't like to be randomly redirected. Only redirect people when absolutely needed. If you start redirecting people randomly they will never go to your site again.

我也想指出,人们不喜欢被随机地重定向。只有在需要的时候才重定向。如果你开始随机地重新引导人们,他们就再也不会去你的网站了。

The next part is hypothetical:

下一部分是假设:

You also may get reported as a malicious site. If that happens then when people click on a link to your site the users browser may warn them that your site is malicious. What may also happen is search engines may start dropping your rating if people are reporting a bad experience on your site.

你也可能被举报为恶意网站。如果出现这种情况,当人们点击链接到你的网站时,用户浏览器会警告他们你的网站是恶意的。如果人们在你的网站上报告不好的经历,搜索引擎可能会开始降低你的评级。

Please review Google Webmaster Guidelines about redirects: https://support.google.com/webmasters/answer/2721217?hl=en&ref_topic=6001971

请查看谷歌网站的重定向指导方针:https://support.google.com/webmasters/answer/2721217? hlen&ref_topic6001971。

Here is a fun little page that kicks you out of the page.

这里有一个有趣的小页面,可以把你踢出页面。

<!DOCTYPE html>
<html>
    <head>
        <title>Go Away</title>
    </head>
    <body>
        <h1>Go Away</h1>
        <script>
            setTimeout(function(){
                window.history.back();
            }, 3000);
        </script>
    </body>
</html>

If you combine the two page examples together you would have an infant loop of rerouting that will guarantee that your user will never want to use your site ever again.

如果您将两个页面示例结合在一起,您就会有一个重新运行的婴儿循环,这将保证您的用户再也不想使用您的站点了。

#12


127  

var url = 'asdf.html';
window.location.href = url;

#13


115  

You can do that without jQuery as:

无需jQuery,可以这样做:

window.location = "http://yourdomain.com";

And if you want only jQuery then you can do it like:

如果你只需要jQuery,你可以这样做:

$jq(window).attr("location","http://yourdomain.com");

#14


114  

This works with jQuery:

这与jQuery:

$(window).attr("location", "http://google.fr");

#15


85  

Basically jQuery is just a JavaScript framework and for doing some of the things like redirection in this case, you can just use pure JavaScript, so in that case you have 3 options using vanilla JavaScript:

基本上,jQuery只是一个JavaScript框架,在这种情况下,你可以使用纯JavaScript,所以在这种情况下,你可以使用3种选择:

1) Using location replace, this will replace the current history of the page, means that it is not possible to use the back button to go back to the original page.

1)使用位置替换,这将取代当前页面的历史,意味着不可能使用back按钮返回到原始页面。

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

2) Using location assign, this will keep the history for you and with using back button, you can go back to the original page:

2)使用位置分配,这将为您保留历史,并使用后退按钮,您可以回到原来的页面:

window.location.assign("http://*.com");

3) I recommend using one of those previous ways, but this could be the third option using pure JavaScript:

3)我推荐使用以前的方法之一,但这可能是使用纯JavaScript的第三个选项:

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

You can also write a function in jQuery to handle it, but not recommended as it's only one line pure JavaScript function, also you can use all of above functions without window if you are already in the window scope, for example window.location.replace("http://*.com"); could be location.replace("http://*.com");

您还可以在jQuery中编写一个函数来处理它,但不推荐它只是一行纯JavaScript函数,如果您已经在窗口范围内,也可以使用上面所有的函数,例如window.location.replace(“http://*.com”);可能是location.replace(“http://*.com”);

Also I show them all on the image below:

我也在下面的图片中展示了它们:

如何重定向到另一个网页?

#16


70  

# HTML Page Redirect Using jQuery/JavaScript

# HTML页面重定向使用jQuery/JavaScript。

Try this example code:

试试这个示例代码:

function YourJavaScriptFunction()
{
    var i = $('#login').val();
    if (i == 'login')
        window.location = "login.php";
    else
        window.location = "Logout.php";
}

If you want to give a complete URL as window.location = "www.google.co.in";.

如果您想要提供一个完整的URL作为窗口。位置= " www.google.co.in ";。

#17


66  

So, the question is how to make a redirect page, and not how to redirect to a website?

所以,问题是如何做一个重定向页面,而不是如何重定向到一个网站?

You only need to use JavaScript for this. Here is some tiny code that will create a dynamic redirect page.

您只需要使用JavaScript就可以了。下面是一些可以创建动态重定向页面的小代码。

<script>
    var url = window.location.search.split('url=')[1]; // Get the URL after ?url=
    if( url ) window.location.replace(url);
</script>

So say you just put this snippet into a redirect/index.html file on your website you can use it like so.

因此,假设您将这个代码片段放入一个重定向/索引中。在你的网站上的html文件你可以这样使用它。

http://www.mywebsite.com/redirect?url=http://*.com

http://www.mywebsite.com/redirect?url=http:/ / *.com

And if you go to that link it will automatically redirect you to *.com.

如果你去那个链接,它会自动把你转到*.com。

Link to Documentation

链接到文档

And that's how you make a Simple redirect page with JavaScript

这就是如何用JavaScript创建一个简单的重定向页面。

Edit:

编辑:

There is also one thing to note. I have added window.location.replace in my code because I think it suits a redirect page, but, you must know that when using window.location.replace and you get redirected, when you press the back button in your browser it will not got back to the redirect page, and it will go back to the page before it, take a look at this little demo thing.

还有一点值得注意。我有添加window.location。替换我的代码,因为我认为它适合重定向页面,但是,您必须知道在使用windows .location时。当你在浏览器中按下后退按钮时,它不会返回到重定向页面,它会回到之前的页面,看一下这个小演示。

Example:

例子:

The process: store home => redirect page to google => google

进程:存储home =>重定向页面到谷歌=>谷歌。

When at google: google => back button in browser => store home

当在谷歌:谷歌= >back按钮在浏览器=>商店主页。

So, if this suits your needs then everything should be fine. If you want to include the redirect page in the browser history replace this

所以,如果这符合你的需要,那么一切都应该没问题。如果您想要在浏览器历史中包含重定向页面,请替换它。

if( url ) window.location.replace(url);

with

if( url ) window.location.href = url;

#18


62  

On your click function, just add:

在你的点击功能上,只需添加:

window.location.href = "The URL where you want to redirect";
$('#id').click(function(){
    window.location.href = "http://www.google.com";
});

#19


52  

Try this:

试试这个:

location.assign("http://www.google.com");

Code snippet of example.

代码片段的例子。

#20


50  

You need to put this line in your code:

你需要在代码中加入这一行:

$(location).attr("href","http://*.com");

If you don't have jQuery, go JavaScript with:

如果没有jQuery,可以使用JavaScript:

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

#21


49  

jQuery is not needed. You can do this:

jQuery是完全没有必要的。你可以这样做:

window.open("URL","_self","","")

It is that easy!

那就是简单!

The best way to initiate an HTTP request is with document.loacation.href.replace('URL').

启动HTTP请求的最好方法是使用document. loac.href .replace('URL')。

#22


46  

First write properly. You want to navigate within an application for another link from your application for another link. Here is the code:

第一次写正确。您希望在应用程序中导航到另一个链接的应用程序。这是代码:

window.location.href = "http://www.google.com";

And if you want to navigate pages within your application then I also have code, if you want.

如果你想在应用程序中导航,那么我也有代码。

#23


45  

You can redirect in jQuery like this:

您可以像这样在jQuery中重定向:

$(location).attr('href', 'http://yourPage.com/');

#24


40  

*****THE ORIGINAL QUESTION WAS - "HOW TO REDIRECT USING JQUERY", HENCE THE ANSWER IMPLEMENTS JQUERY >> COMPLIMENTARY USAGE CASE*****

***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ****

To just redirect to a page with JavaScript:

用JavaScript重定向到页面:

  window.location.href = "/contact/";

Or if you need a delay:

或者如果你需要延迟:

setTimeout(function () {
  window.location.href = "/contact/";
}, 2000);   // Time in milliseconds

jQuery allows you to select elements from a web page with ease. You can find anything you want on a page and then use jQuery to add special effects, react to user actions, or show and hide content inside or outside the element you have selected. All these tasks start with knowing how to select an element or an event.

jQuery允许您轻松地从web页面中选择元素。您可以在页面上找到任何您想要的内容,然后使用jQuery添加特殊效果、对用户操作作出反应,或者显示和隐藏您所选择元素的内部或外部内容。所有这些任务从知道如何选择一个元素或事件开始。

     $('a,img').on('click',function(e){
         e.preventDefault();
         $(this).animate({
             opacity: 0 //Put some CSS animation here
         }, 500);
         setTimeout(function(){
           // OK, finished jQuery staff, let's go redirect
           window.location.href = "/contact/";
         },500);
     });

Imagine someone wrote a script/plugin that is 10000 lines of code?! Well, with jQuery you can connect to this code with just a line or two.

想象有人写了一个脚本/插件,那是10000行代码?!用jQuery,你可以用一两行代码连接到这个代码。

#25


38  

In JavaScript and jQuery we can use the following code to redirect the one page to another page:

在JavaScript和jQuery中,我们可以使用以下代码将一个页面重定向到另一个页面:

window.location.href="http://google.com";
window.location.replace("page1.html");

#26


37  

ECMAScript 6 + jQuery, 85 bytes

$({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")

Please don't kill me, this is a joke. It's a joke. This is a joke.

请不要杀我,这是个玩笑。这是一个笑话。这是一个笑话。

This did "provide an answer to the question", in the sense that it asked for a solution "using jQuery" which in this case entails forcing it into the equation somehow.

这确实“提供了一个问题的答案”,从某种意义上说,它需要一个“使用jQuery”的解决方案,而在这种情况下,它需要以某种方式迫使它进入这个等式。

Ferrybig apparently needs the joke explained (still joking, I'm sure there are limited options on the review form), so without further ado:

Ferrybig显然需要这个笑话的解释(还在开玩笑,我相信在评论表单上有一些有限的选项),所以不要再多说了:

Other answers are using jQuery's attr() on the location or window objects unnecessarily.

其他的答案是使用jQuery的attr()在不必要的位置或窗口对象上。

This answer also abuses it, but in a more ridiculous way. Instead of using it to set the location, this uses attr() to retrieve a function that sets the location.

这个答案也滥用了它,但以一种更荒谬的方式。它使用attr()来检索设置位置的函数,而不是使用它来设置位置。

The function is named jQueryCode even though there's nothing jQuery about it, and calling a function somethingCode is just horrible, especially when the something is not even a language.

即使没有jQuery,函数也被命名为jQueryCode,调用函数是非常可怕的,特别是当某些东西甚至不是语言的时候。

The "85 bytes" is a reference to Code Golf. Golfing is obviously not something you should do outside of code golf, and furthermore this answer is clearly not actually golfed.

“85字节”是代码高尔夫的参考。打高尔夫球显然不是你在打高尔夫球时应该做的事,而且这个答案显然不是高尔夫球。

Basically, cringe.

基本上,畏缩。

#27


35  

Javascript:

Javascript:

window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');

Jquery:

Jquery:

var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window

#28


34  

Here is a time-delay redirection. You can set the delay time to whatever you want:

这是一个时延重定向。您可以将延迟时间设置为您想要的任何内容:

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Your Document Title</title>
    <script type="text/javascript">
        function delayer(delay) {
            onLoad = setTimeout('window.location.href = "http://www.google.com/"', delay);
        }
    </script>
</head>

<body>
    <script>
        delayer(8000)
    </script>
    <div>You will be redirected in 8 seconds!</div>
</body>

</html>

#29


33  

I just had to update this ridiculousness with yet another newer jQuery method:

我只需要用另一种新的jQuery方法来更新这个荒谬的方法:

var url = 'http://www.fiftywaystoleaveyourlocation.com';
$(location).prop('href', url);

#30


32  

There are three main ways to do this,

有三种主要的方法,

window.location.href='blaah.com';
window.location.assign('blaah.com');

and...

和…

window.location.replace('blaah.com');

The last one is best, for a traditional redirect, because it will not save the page you went to before being redirected in your search history. However, if you just want to open a tab with JavaScript, you can use any of the above.1

最后一个是最好的,对于一个传统的重定向,因为它不会保存您在被重定向到您的搜索历史之前所访问的页面。但是,如果您只想打开一个带有JavaScript的选项卡,您可以使用上面的任何一个。

EDIT: The window prefix is optional.

编辑:窗口前缀是可选的。


转载请注明本文地址:How do I redirect to another webpage?