简体   繁体   English

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

[英]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 将用户从一个页面重定向到另一个页面?

One does not simply redirect using jQuery一个不是简单地使用 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.replace(...)比使用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 重定向,请使用location.replace

For example:例如:

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

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

WARNING: This answer has merely been provided as a possible solution;警告:此答案仅作为一种可能的解决方案提供; it is obviously not the best solution, as it requires jQuery.这显然不是最好的解决方案,因为它需要 jQuery。 Instead, prefer the pure JavaScript solution.相反,更喜欢纯 JavaScript 解决方案。

$(location).prop('href', 'http://stackoverflow.com')

Standard "vanilla" JavaScript way to redirect a page重定向页面的标准“香草”JavaScript 方式

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

Or more simply: (since window is Global)或更简单地说:(因为window是全局的)

location.href = 'newPage.html';

If you are here because you are losing HTTP_REFERER when redirecting, keep reading:如果您在这里是因为在重定向时丢失了HTTP_REFERER,请继续阅读:

(Otherwise ignore this last part) (否则忽略这最后一部分)


The following section is for those using HTTP_REFERER as one of many security measures (although it isn't a great protective measure).以下部分适用于那些使用HTTP_REFERER作为许多安全措施之一的人(尽管它不是一个很好的保护措施)。 If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).如果您使用的是Internet Explorer 8或更低版本,则在使用任何形式的 JavaScript 页面重定向(location.href 等)时,这些变量会丢失。

Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER.下面我们将为IE8 及更低版本实现一个替代方案,这样我们就不会丢失 HTTP_REFERER。 Otherwise, you can almost always simply use window.location.href .否则,您几乎总是可以简单地使用window.location.href

Testing against HTTP_REFERER (URL pasting, session, etc.) can help tell whether a request is legitimate.针对HTTP_REFERER (URL 粘贴、会话等)进行测试可以帮助判断请求是否合法。 ( Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments) 注意:还有一些方法可以解决/欺骗这些引荐来源网址,正如评论中的 droop 链接所指出的那样)


Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)简单的跨浏览器测试解决方案(回退到 Internet Explorer 9+ 和所有其他浏览器的 window.location.href)

Usage: redirect('anotherpage.aspx');用法: redirect('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; 
    }
}

There are lots of ways of doing this.有很多方法可以做到这一点。

// 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')

这适用于每个浏览器:

window.location.href = 'your_url';

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.如果您希望通过 AJAX 更改分页数据,这就是 jQuery 的用武之地。您要做的是将单击处理程序添加到对应于不同页面的每个锚标记。 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.此单击处理程序将调用一些 jQuery 代码,该代码通过 AJAX 获取下一页并使用新数据更新表。 The example below assumes that you have a web service that returns the new page data.下面的示例假设您有一个返回新页面数据的 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
    });
});

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.我也认为location.replace(URL)是最好的方法,但是如果你想通知搜索引擎你的重定向(他们不分析 JavaScript 代码来查看重定向)你应该添加rel="canonical"元标记到您的网站。

Adding a noscript section with a HTML refresh meta tag in it, is also a good solution.添加一个带有 HTML 刷新元标记的 noscript 部分也是一个很好的解决方案。 I suggest you to use this JavaScript redirection tool to create redirections.我建议你使用这个JavaScript 重定向工具来创建重定向。 It also has Internet Explorer support to pass the HTTP referrer.它还支持 Internet Explorer 以传递 HTTP 引荐来源网址。

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.example/"/>
<noscript>
    <meta http-equiv="refresh" content="0;URL=https://yourdomain.example/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
    var url = "https://yourdomain.example/";
    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 -->

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的控制台中即可探索此 window 或 window.location 对象。

JavaScript provides you many methods to retrieve and change the current URL which is displayed in browser's address bar. JavaScript 为您提供了许多方法来检索和更改显示在浏览器地址栏中的当前 URL。 All these methods uses the Location object, which is a property of the Window object.所有这些方法都使用 Location 对象,它是 Window 对象的一个​​属性。 You can create a new Location object that has the current URL as follows..您可以创建一个具有当前 URL 的新 Location 对象,如下所示。

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.协议——指定用于访问 Internet 上的资源的协议名称。 (HTTP (without SSL) or HTTPS (with SSL)) (HTTP(无 SSL)或 HTTPS(有 SSL))

  2. hostname -- Host name specifies the host that owns the resource.主机名——主机名指定拥有资源的主机。 For example, www.stackoverflow.com.例如,www.stackoverflow.com。 A server provides services using the name of the host.服务器使用主机名提供服务。

  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. port -- 一个端口号,用于识别 Internet 或其他网络消息到达服务器时要转发到的特定进程。

  4. pathname -- The path gives info about the specific resource within the host that the Web client wants to access.路径名——路径提供有关 Web 客户端想要访问的主机中的特定资源的信息。 For example, stackoverflow.com/index.html.例如,stackoverflow.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 (#). hash -- URL 的锚点部分,包括井号 (#)。

With these Location object properties you can access all of these URL components使用这些 Location 对象属性,您可以访问所有这些 URL 组件

  1. hash -Sets or returns the anchor portion of a URL. hash - 设置或返回 URL 的锚点部分。
  2. host -Sets or returns the hostname and port of a URL. host - 设置或返回 URL 的主机名和端口。
  3. hostname -Sets or returns the hostname of a URL.主机名- 设置或返回 URL 的主机名。
  4. href -Sets or returns the entire URL. href - 设置或返回整个 URL。
  5. pathname -Sets or returns the path name of a URL. pathname - 设置或返回 URL 的路径名。
  6. port -Sets or returns the port number the server uses for a URL. port - 设置或返回服务器用于 URL 的端口号。
  7. protocol -Sets or returns the protocol of a URL.协议- 设置或返回 URL 的协议。
  8. search -Sets or returns the query portion of a URL search - 设置或返回 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现在,如果您想更改页面或将用户重定向到其他页面,您可以使用 Location 对象的href属性,如下所示

You can use the href property of the Location object.您可以使用 Location 对象的 href 属性。

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

Location Object also have these three methods Location Object也有这三个方法

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

You can use assign() and replace methods also to redirect to other pages like these您还可以使用 assign() 和 replace 方法重定向到其他页面,例如这些

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

location.replace("http://www.stackoverflow.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. assign() 和 replace() 有何不同-- replace() 方法和 assign() 方法() 的区别在于 replace() 从文档历史记录中删除当前文档的 URL,意味着不能使用“返回”按钮导航回原始文档。 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.因此,如果您想加载一个新文档,并希望提供导航回原始文档的选项,请使用 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。

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 个使用 vanilla JavaScript 的选项:

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)使用 location replace ,这将替换页面的当前历史记录,意味着无法使用返回按钮返回到原始页面。

window.location.replace("http://stackoverflow.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)使用 location assign ,这将为您保留历史记录,并使用后退按钮,您可以返回原始页面:

window.location.assign("http://stackoverflow.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://stackoverflow.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://stackoverflow.com");您也可以在jQuery中编写一个函数来处理它,但不推荐,因为它只有一行纯JavaScript函数,如果您已经在窗口范围内,您也可以在没有窗口的情况下使用上述所有函数,例如window.location.replace("http://stackoverflow.com"); could be location.replace("http://stackoverflow.com");可能是location.replace("http://stackoverflow.com");

Also I show them all on the image below:我也将它们全部显示在下图中:

location.replace location.assign

Should just be able to set using window.location .应该可以使用window.location进行设置。

Example:例子:

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

Here is a past post on the subject: How do I redirect to another webpage?这是有关该主题的过去帖子: 如何重定向到另一个网页?

Before I start, jQuery is a JavaScript library used for DOM manipulation.在开始之前,jQuery 是一个用于 DOM 操作的 JavaScript 库。 So you should not be using jQuery for a page redirect.所以你不应该使用 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 毫秒后重定向到Google

<!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 .如果您希望用户能够返回重定向页面,请使用window.location.hrefwindow.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.但是如果页面自动重定向,那么您应该使用替换,以便用户可以使用后退按钮而不会被迫返回重定向发送的页面。

You can also use meta data to run a page redirect as followed.您还可以使用元数据来运行页面重定向,如下所示。

META Refresh元刷新

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

META Location元位置

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

BASE Hijacking基地劫持

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

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 paragraph 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请查看有关重定向的 Google 网站管理员指南:https: //support.google.com/webmasters/answer/2721217?hl=en&ref_topic=6001971

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.如果您将两个页面示例组合在一起,您将拥有一个重新路由的婴儿循环,这将保证您的用户永远不会想要再次使用您的网站。

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

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

这适用于 jQuery:

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

# HTML Page Redirect Using jQuery/JavaScript Method # 使用 jQuery/JavaScript 方法的 HTML 页面重定向

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 作为window.location = "www.google.co.in"; . .

Original question: "How to redirect using jQuery?", hence the answer implements jQuery >> Complimentary usage case.原始问题: “如何使用 jQuery 重定向?”,因此答案实现了 jQuery >> 免费用例。


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. jQuery 允许您轻松地从网页中选择元素。 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.您可以在页面上找到您想要的任何内容,然后使用 jQuery 来添加特殊效果、对用户操作做出反应,或者在您选择的元素内部或外部显示和隐藏内容。 All these tasks start with knowing how to select an element or an event .所有这些任务都从知道 如何选择元素或事件开始。

$('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 with 10000 lines of code.想象一下有人用 10000 行代码编写了一个脚本/插件。 With jQuery you can connect to this code with just a line or two.使用 jQuery,您只需一两行即可连接到此代码。

You need to put this line in your code:您需要将此行放入您的代码中:

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

If you don't have jQuery, go with JavaScript:如果您没有 jQuery,请使用 JavaScript:

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

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.您只需要为此使用 JavaScript。 Here is some tiny code that will create a dynamic redirect page.这是一些将创建动态重定向页面的小代码。

<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.因此,假设您只是将此代码段放入您网站上的redirect/index.html文件中,您可以像这样使用它。

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

And if you go to that link it will automatically redirect you to stackoverflow.com .如果您转到该链接,它会自动将您重定向到stackoverflow.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.replace ,因为我认为它适合重定向页面,但是,您必须知道,当使用window.location.replace并被重定向时,当您在浏览器中按下后退按钮时,它不会回到重定向页面,它会回到它之前的页面,看看这个小演示。

Example:例子:

The process: store home => redirect page to google => google过程:商店首页=>将页面重定向到谷歌=>谷歌

When at google: google => back button in browser => store home在谷歌时:谷歌=>浏览器中的后退按钮=>商店主页

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;

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";
});

Try this:尝试这个:

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

Code snippet of example . 示例代码片段

jQuery is not needed.不需要 jQuery。 You can do this:你可以这样做:

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.loacation.href.replace('URL')

Using JavaScript:使用 JavaScript:

Method 1:方法一:

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

Method 2:方法二:

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

Using jQuery:使用 jQuery:

Method 1: $(location)方法一:$(location)

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

Method 2: Reusable Function方法二:可重用函数

jQuery.fn.redirectTo = function(url){
    window.location.href = url;
}

jQuery(window).redirectTo("http://google.com");

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.如果你想在你的应用程序中导航页面,那么我也有代码,如果你愿意的话。

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

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

JavaScript is very extensive. JavaScript 非常广泛。 If you want to jump to another page you have three options.如果你想跳转到另一个页面,你有三个选项。

 window.location.href='otherpage.com';
 window.location.assign('otherpage.com');
 //and...

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

As you want to move to another page, you can use any from these if this is your requirement.当您想移动到另一个页面时,如果这是您的要求,您可以使用其中的任何一个。 However all three options are limited to different situations.然而,所有三个选项都限于不同的情况。 Chose wisely according to your requirement.根据您的要求明智地选择。

If you are interested in more knowledge about the concept, you can go through further.如果您对有关该概念的更多知识感兴趣,可以进一步了解。

window.location.href; // Returns the href (URL) of the current page
window.location.hostname; // Returns the domain name of the web host
window.location.pathname; // Returns the path and filename of the current page
window.location.protocol; // Returns the web protocol used (http: or https:)
window.location.assign; // Loads a new document
window.location.replace; // RReplace the current location with new one.

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

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:查询:

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

ECMAScript 6 + jQuery, 85 bytes ECMAScript 6 + jQuery,85 字节

$({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.其他答案是不必要地在locationwindow对象上使用 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.该函数被命名为jQueryCode ,即使它没有任何关于它的 jQuery,并且调用函数somethingCode实在是太可怕了,尤其是当某物甚至不是一种语言时。

The "85 bytes" is a reference to Code Golf. “85 bytes”是对 Code Golf 的引用。 Golfing is obviously not something you should do outside of code golf, and furthermore this answer is clearly not actually golfed.打高尔夫球显然不是你应该在代码高尔夫球之外做的事情,而且这个答案显然不是真正的打高尔夫球。

Basically, cringe.基本上,畏缩。

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>

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.但是,如果您只想使用 JavaScript 打开选项卡,则可以使用上述任何一种。 1 1

EDIT: The window prefix is optional.编辑: window前缀是可选的。

I just had to update this ridiculousness with yet another newer jQuery method: 我只需要用另一种新的jQuery方法来更新这种荒谬性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM