1. 程式人生 > >如何重定向到另一個網頁?

如何重定向到另一個網頁?

英文原文地址為: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://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.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://stackoverflow.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>

enter image description here

  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.stackoverflow.com. A server provides services using the name of the host.

    主機名——主機名指定擁有資源的主機。例如,www.stackoverflow.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, stackoverflow.com/index.html.

    路徑名——路徑給出了Web客戶機想要訪問的主機中特定資源的資訊。例如,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 (#).

    雜湊——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.stackoverflow.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.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. 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://stackoverflow.com/";

Here is a past post on the subject:

這裡有一篇關於這個主題的文章:

#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,通常也不會修復出現在它們中的錯誤。

它是在這裡找到的: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 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):

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.

你也可能被舉報為惡意網站。如果出現這種情況,當人們點選連結到你的網站時,使用者瀏覽器會警告他們你的網站是惡意的。如果人們在你的網站上報告不好的經歷,搜尋引擎可能會開始降低你的評級。

請檢視谷歌網站的重定向指導方針: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://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)使用位置分配,這將為您保留歷史,並使用後退按鈕,您可以回到原來的頁面:

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"); could be location.replace("http://stackoverflow.com");

您還可以在jQuery中編寫一個函式來處理它,但不推薦它只是一行純JavaScript函式,如果您已經在視窗範圍內,也可以使用上面所有的函式,例如window.location.replace(“http://stackoverflow.com”);可能是location.replace(“http://stackoverflow.com”);

Also I show them all on the image below:

我也在下面的圖片中展示了它們:

location.replace

#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://stackoverflow.com

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。

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

程式碼片段的例子。

#20

50  

You need to put this line in your code:

你需要在程式碼中加入這一行:

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

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

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

window.location.replace("http://stackoverflow.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?