【问题标题】:Get current URL with jQuery?使用 jQuery 获取当前 URL?
【发布时间】:2010-09-29 04:53:07
【问题描述】:

我正在使用 jQuery。如何获取当前 URL 的路径并将其分配给变量?

示例网址:

http://localhost/menuname.de?foo=bar&number=0

【问题讨论】:

  • 我认为问题应该恢复到询问jQuery,因为有一个答案,无论是否需要jQuery来完成任务。
  • @goodeye 不,没有 jQuery 方法来获取位置;从 jQuery 错误跟踪器开始:»它可能有效,但从未得到支持或记录。只需使用更快、更简单、更容易理解的 document.location.href。« 换句话说,有些人使用 jQuery 来获取位置,但他们依赖于错误,而不是功能。见:bugs.jquery.com/ticket/7858

标签: javascript jquery url


【解决方案1】:

要获取路径,可以使用:

var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url      = window.location.href;     // Returns full URL (https://example.com/path/example.html)
var origin   = window.location.origin;   // Returns base URL (https://example.com)

【讨论】:

  • jQuery 并没有扼杀它,而是赋予了 Javascript 新的生命。新的 C#/Java 程序员了解指针吗?不,他们需要吗?不是真的,较新的抽象足够强大,这无关紧要..
  • "How do I XYZ in jQuery" 答案是纯 JavaScript 很常见。你可能知道如何用普通的 javascript 做一些事情;但是,由于浏览器的不一致,您可能更喜欢使用“jQuery”方式。我记得在 jQuery 或框架之前,我会先检查浏览器,然后用几种方法做我想做的事。 jQuery 也在杀死普通的 js……是的,谢天谢地,但它也让它变得可用。
  • 这不适用于完整的网址。例如。对于“mail.google.com/mail/u/0/#mbox/13005b79fe72f448”,这只会返回 /mail/u/0
  • Ummm,... window.location.pathname 只获取 URL 的“?”并且没有得到问题中询问的查询参数。
【解决方案2】:

纯 jQuery 风格:

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

位置对象还具有其他属性,例如主机、哈希、协议和路径名。

【讨论】:

  • 显然,不支持在 jQuery 中使用 $(location),建议不要使用:bugs.jquery.com/ticket/7858
  • @Peter Bug 因无效而关闭。
  • @mc10:“无效”部分适用于支持 $(location) 的请求;这不应该被使用。
  • 这个答案是不需要的,可以更新问答不使用jquery。原因可以在这里找到bugs.jquery.com/ticket/7858#comment:4
  • @HaralanDobrev:你不应该在现场使用.attr()。 (1)它不是一个元素,所以$(location) 充其量是阴暗的,(2)即使它有效,你也应该使用.prop() 来获取属性。 .attr() 用于 HTML 属性。
【解决方案3】:
http://www.refulz.com:8082/index.php#tab2?foo=789

Property    Result
------------------------------------------
host        www.refulz.com:8082
hostname    www.refulz.com
port        8082
protocol    http:
pathname    index.php
href        http://www.refulz.com:8082/index.php#tab2
hash        #tab2
search      ?foo=789

var x = $(location).attr('<property>');

这只有在你有 jQuery 时才有效。例如:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
  $(location).attr('href');      // http://www.refulz.com:8082/index.php#tab2
  $(location).attr('pathname');  // index.php
</script>
</html>

【讨论】:

【解决方案4】:

如果您需要 URL 中的哈希参数,window.location.href 可能是更好的选择。

window.location.pathname
=> /search

window.location.href 
 => www.website.com/search#race_type=1

【讨论】:

  • 如果有人只需要哈希标签而不是可以调用 window.location.href
  • 我认为@AmitPatel 的意思是window.location.hash
【解决方案5】:

您需要使用 JavaScript 的内置 window.location 对象。

【讨论】:

  • 这将不会返回 '?' 之后的项目在位置。
  • @majidgeek 在 Firefox、Chrome 和 IE 中为我工作。你能提供一个这种破坏的测试用例吗?
  • 至少可以在控制台确认window.location.pathname?之后没有检索到任何东西
【解决方案6】:

只要在 JavaScript 中添加这个函数,它就会返回当前路径的绝对路径。

function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}

我希望它对你有用。

【讨论】:

  • 这对于我懒惰地拥有一些硬编码的基本 URL 的脚本很有帮助。我不喜欢在根目录上没有尾随'/'并将其插入路径中,所以我只做了第二行var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/'));
【解决方案7】:

window.location 是 javascript 中的一个对象。它返回以下数据

window.location.host          #returns host
window.location.hostname      #returns hostname
window.location.path          #return path
window.location.href          #returns full current url
window.location.port          #returns the port
window.location.protocol      #returns the protocol

在jquery中你可以使用

$(location).attr('host');        #returns host
$(location).attr('hostname');    #returns hostname
$(location).attr('path');        #returns path
$(location).attr('href');        #returns href
$(location).attr('port');        #returns port
$(location).attr('protocol');    #returns protocol

【讨论】:

  • windo.location.origin 呢?
【解决方案8】:

这是一个比许多人想象的更复杂的问题。一些浏览器支持通过window.locationdocument.location 访问的内置JavaScript 位置对象和相关参数/方法。但是,不同风格的 Internet Explorer (6,7) 不以相同的方式支持这些方法,(window.location.href?window.location.replace() 不支持)因此您必须始终通过编写条件代码来以不同方式访问它们- 按住 Internet Explorer。

所以,如果您有 jQuery 可用并已加载,您不妨使用 jQuery(位置),正如其他人提到的那样,因为它解决了这些问题。但是,如果您正在通过 JavaScript 进行一些客户端地理定位重定向(即使用 Google Maps API 和位置对象方法),那么您可能不想加载整个 jQuery 库并编写条件代码检查每个版本的 Internet Explorer/Firefox/等。

Internet Explorer 让前端编码猫不开心,但 jQuery 是一盘牛奶。

【讨论】:

  • 另外:bugs.jquery.com/ticket/8138。在 jQuery 1.8.0 源代码中有注释: // #8138,如果已设置 document.domain,IE 可能会在访问 // window.location 中的字段时抛出异常。
【解决方案9】:

仅对于主机名,使用:

window.location.hostname

【讨论】:

    【解决方案10】:

    这也可以:

    var currentURL = window.location.href;
    

    【讨论】:

    • 这给出了大多数人寻找的完整 URL。
    【解决方案11】:

    java-script 提供了许多方法来检索显示在浏览器地址栏中的当前 URL。

    测试网址:

    http://
    stackoverflow.com/questions/5515310/get-current-url-with-jquery/32942762
    ?
    rq=1&page=2&tab=active&answertab=votes
    #
    32942762
    
    resourceAddress.hash();
    console.log('URL Object ', webAddress);
    console.log('Parameters ', param_values);
    

    功能:

    var webAddress = {};
    var param_values = {};
    var protocol = '';
    var resourceAddress = {
    
        fullAddress : function () {
            var addressBar = window.location.href;
            if ( addressBar != '' && addressBar != 'undefined') {
                webAddress[ 'href' ] = addressBar;
            }
        },
        protocol_identifier : function () { resourceAddress.fullAddress();
    
            protocol = window.location.protocol.replace(':', '');
            if ( protocol != '' && protocol != 'undefined') {
                webAddress[ 'protocol' ] = protocol;
            }
        },
        domain : function () {      resourceAddress.protocol_identifier();
    
            var domain = window.location.hostname;
            if ( domain != '' && domain != 'undefined' && typeOfVar(domain) === 'string') {
                webAddress[ 'domain' ] = domain;
                var port = window.location.port;
                if ( (port == '' || port == 'undefined') && typeOfVar(port) === 'string') {
                    if(protocol == 'http') port = '80';
                    if(protocol == 'https') port = '443';           
                }
                webAddress[ 'port' ] = port;
            }
        },
        pathname : function () {        resourceAddress.domain();
    
            var resourcePath = window.location.pathname;
            if ( resourcePath != '' && resourcePath != 'undefined') {
                webAddress[ 'resourcePath' ] = resourcePath;
            }
        },
        params : function () {      resourceAddress.pathname();
    
            var v_args = location.search.substring(1).split("&");
    
            if ( v_args != '' && v_args != 'undefined')
            for (var i = 0; i < v_args.length; i++) {
                var pair = v_args[i].split("=");
    
                if ( typeOfVar( pair ) === 'array' ) {
                    param_values[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
                }
            }
            webAddress[ 'params' ] = param_values;
        },
        hash : function () {        resourceAddress.params();
    
            var fragment = window.location.hash.substring(1);
            if ( fragment != '' && fragment != 'undefined')
                webAddress[ 'hash' ] = fragment;        
        }
    };
    function typeOfVar (obj) {
          return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
    }
    
    • protocol « Web-browsers 使用 Internet 协议,遵循一些规则在 WebHosted 应用程序和 Web 客户端(浏览器)之间进行通信。 (http = 80、https (SSL) = 443、ftp = 21 等)

    EX:使用默认端口号

    <protocol>//<hostname>:<port>/<pathname><search><hash>
    https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
    http://stackoverflow.com:80/
    
    • (//) « 主机是 Internet 上的端点(资源所在的机器)的名称。 www.stackoverflow.com - DNS 应用程序的 IP 地址 (OR) localhost:8080 - localhost

    域名是您根据域名系统 (DNS) 树的规则和程序注册的域名。使用 IP 地址管理您的域的人的 DNS 服务器,用于寻址目的。在 DNS 服务器层次结构中 stackoverlfow.com 的根名称是 com。

    gTLDs      - com « stackoverflow (OR) in « co « google
    

    您必须维护在主机文件中不是 PUBLIC 的域的本地系统。 localhost.yash.com « localhsot - subdomain(web-server), yash.com - maindomain(Proxy-Server). myLocalApplication.com 172.89.23.777

    • (/) « 该路径提供有关 Web 客户端想要访问的主机内特定资源的信息
    • (?) « 可选查询是传递由分隔符 (&) 分隔的一系列属性值对。
    • (#) « 可选片段通常是特定元素的 id 属性,Web 浏览器会将这个元素滚动到视图中。

    如果参数有 Epoch ?date=1467708674 则使用。

    var epochDate = 1467708674; var date = new Date( epochDate );
    

    网址


    带有用户名:密码的认证url,如果用户名/密码包含@符号
    喜欢:

    Username = `my_email@gmail`
    Password = `Yash@777`
    

    那么您需要将 @ 的 URL 编码为 %40Refer...

    http://my_email%40gmail.com:Yash%40777@www.my_site.com
    

    encodeURI() (vs) encodeURIComponent() 示例

    var testURL = "http:my_email@gmail:Yash777@//stackoverflow.com?tab=active&page=1#32942762";
    
    var Uri = "/:@?&=,#", UriComponent = "$;+", Unescaped = "(-_.!~*')"; // Fixed
    var encodeURI_Str = encodeURI(Uri) +' '+ encodeURI( UriComponent ) +' '+ encodeURI(Unescaped);
    var encodeURIComponent_Str =  encodeURIComponent( Uri ) +' '+ encodeURIComponent( UriComponent ) +' '+ encodeURIComponent( Unescaped );
    console.log(encodeURI_Str, '\n', encodeURIComponent_Str);
    /*
     /:@?&=,# +$; (-_.!~*') 
     %2F%3A%40%3F%26%3D%2C%23 %2B%24%3B (-_.!~*')
    */
    

    【讨论】:

      【解决方案12】:

      您可以记录 window.location 并查看所有选项,仅用于 URL 使用:

      window.location.origin
      

      对于整个路径使用:

      window.location.href
      

      还有位置。__

      .host
      .hostname
      .protocol
      .pathname
      

      【讨论】:

      • 不应使用它,因为 location.origin 在 Internet Explorer 中不起作用
      【解决方案13】:

      这将使用 JavaScript/jQuery 返回当前页面的绝对 URL

      • document.URL

      • $("*").context.baseURI

      • location.href

      【讨论】:

        【解决方案14】:

        我有这个去除 GET 变量。

        var loc = window.location;
        var currentURL = loc.protocol + '//' + loc.host + loc.pathname;
        

        【讨论】:

          【解决方案15】:

          如果有人想将URL 和哈希标签连接起来,结合两个函数:

          var pathname = window.location.pathname + document.location.hash;
          

          【讨论】:

          • 澄清一下:你根本不需要使用jQuery,上面的javascript函数会返回OP所要求的?
          【解决方案16】:

          您可以简单地使用 js 本身获取您的路径,window.locationlocation 将为您提供当前 URL 的对象

          console.log("Origin - ",location.origin);
          console.log("Entire URL - ",location.href);
          console.log("Path Beyond URL - ",location.pathname);

          【讨论】:

            【解决方案17】:

            所有浏览器都支持 Javascript 窗口对象。它定义了浏览器的窗口。

            全局对象和函数自动成为窗口对象的一部分。

            所有全局变量都是窗口对象的属性,所有全局函数都是它的方法。

            整个 HTML 文档也是一个窗口属性。

            所以你可以使用 window.location 对象来获取所有 url 相关的属性。

            Javascript

            console.log(window.location.host);     //returns host
            console.log(window.location.hostname);    //returns hostname
            console.log(window.location.pathname);         //return path
            console.log(window.location.href);       //returns full current url
            console.log(window.location.port);         //returns the port
            console.log(window.location.protocol)     //returns the protocol

            JQuery

            console.log("host = "+$(location).attr('host'));
            console.log("hostname = "+$(location).attr('hostname'));
            console.log("pathname = "+$(location).attr('pathname')); 
            console.log("href = "+$(location).attr('href'));   
            console.log("port = "+$(location).attr('port'));   
            console.log("protocol = "+$(location).attr('protocol'));
            &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"&gt;&lt;/script&gt;

            【讨论】:

            • 我看到 location.pathname 你在哪里使用 location.path - 这个答案需要更新吗?
            • @Edward 更新
            【解决方案18】:
             var currenturl = jQuery(location).attr('href');
            

            【讨论】:

              【解决方案19】:

              这是一个使用 jQuery 和 JavaScript 获取当前 URL 的示例:

              $(document).ready(function() {
              
                  //jQuery
                  $(location).attr('href');
              
                  //Pure JavaScript
                  var pathname = window.location.pathname;
              
                  // To show it in an alert window
                  alert(window.location);
              });
              
              
              $.getJSON("idcheck.php?callback=?", { url:$(location).attr('href')}, function(json){
                  //alert(json.message);
              });
              

              【讨论】:

                【解决方案20】:

                从 iframe 中获取父窗口的 URL:

                $(window.parent.location).attr('href');
                

                注意:仅适用于同一域

                【讨论】:

                  【解决方案21】:

                  以下是可以使用的有用代码 sn-ps 的示例——一些示例使用标准 JavaScript 函数并且不特定于 jQuery:

                  8 Useful jQuery Snippets For URL’s & Querystrings

                  【讨论】:

                    【解决方案22】:

                    window.location 会给你当前的URL,你可以从中提取任何你想要的...

                    【讨论】:

                      【解决方案23】:

                      如果你想获取根站点的路径,使用这个:

                      $(location).attr('href').replace($(location).attr('pathname'),'');
                      

                      【讨论】:

                      • 那不是.replace('#.*', '')吗?不仅要删除井号,还要删除它后面的所有内容?
                      【解决方案24】:

                      使用 window.location.href。这将为您提供完整的URL

                      【讨论】:

                        【解决方案25】:

                        var path = location.pathname 返回当前 URL 的路径(不需要 jQuery)。 window.location 的使用是可选的。

                        【讨论】:

                          【解决方案26】:

                          purl.js。这真的很有帮助,也可以使用,具体取决于 jQuery。像这样使用它:

                          $.url().param("yourparam");
                          

                          【讨论】:

                            【解决方案27】:

                            非常常用的前 3 个是

                            1. window.location.hostname 
                            2. window.location.href
                            3. window.location.pathname
                            

                            【讨论】:

                              【解决方案28】:
                              var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
                              

                              【讨论】:

                              • 你应该在你的答案中添加一些解释。
                              【解决方案29】:

                              通过以下代码可以在Jquery中获取当前的URL。

                              $(location).attr('hostname');                //origin URL
                              $(location).attr('pathname');                // path name
                              $(location).attr('hash');                    // everything comes after hash
                              

                              【讨论】:

                                【解决方案30】:
                                // get current URL
                                
                                $(location).attr('href');
                                var pathname = window.location.pathname;
                                alert(window.location);
                                

                                【讨论】:

                                  猜你喜欢
                                  • 1970-01-01
                                  • 2018-10-17
                                  • 2010-11-05
                                  相关资源
                                  最近更新 更多