使用 jQuery 获取当前 URL?

问:

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

示例网址:

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

答1:

huntsbot.com汇聚了国内外优秀的初创产品创意,可按收入、分类等筛选,希望这些产品与实践经验能给您带来灵感。

要获取路径,您可以使用:

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)

位置对象的属性:developer.mozilla.org/en/DOM/window.location

jQuery 并没有扼杀它,而是赋予了 Javascript 新的生命。新的 C#/Java 程序员了解指针吗?不,他们需要吗?不是真的,较新的抽象足够强大,这无关紧要..

“我如何在 jQuery 中进行 XYZ”和纯 JavaScript 的答案很常见。你可能知道如何用普通的 javascript 做一些事情;但是,由于浏览器不一致,您可能更喜欢使用“jQuery”方式。我记得在 jQuery 或框架之前,我会先检查浏览器,然后用几种方法做我想做的事。 jQuery 也在杀死普通的 js……是的,谢天谢地,但它也让它变得可用。

这不适用于完整的网址。例如。对于“mail.google.com/mail/u/0/#mbox/13005b79fe72f448”,这只会返回 /mail/u/0

嗯,... window.location.pathname 只获取 URL 上的“?”并且没有得到问题中询问的查询参数。

答2:

与HuntsBot一起,探索全球自由职业机会–huntsbot.com

纯 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:

打造属于自己的副业,开启自由职业之旅,从huntsbot.com开始!

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('');

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




  $(location).attr('href');      // http://www.refulz.com:8082/index.php#tab2
  $(location).attr('pathname');  // index.php



这与之前的解释相同,但包含对象的所有元素。很好的答案。

路径名应该是 /index.php 而不是 index.php。

+1 jQuery is best quality code ever, if you don't use it your a idiot. jQuery is definitely the way to go.

根据 bugs.jquery.com/ticket/7858,这只是偶然的。此外,attr 应该只用于 DOM 对象,用于可以使用 HTML 属性设置的东西。

答4:

与HuntsBot一起,探索全球自由职业机会–huntsbot.com

如果您需要 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:

保持自己快人一步,享受全网独家提供的一站式外包任务、远程工作、创意产品订阅服务–huntsbot.com

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

这不会在“?”之后返回项目在位置。

@majidgeek 在 Firefox、Chrome 和 IE 中为我工作。你能提供这个破解的测试用例吗?

至少可以在控制台中确认 window.location.pathname 在 ? 之后没有检索到任何内容

答6:

一个优秀的自由职业者,应该有对需求敏感和精准需求捕获的能力,而huntsbot.com提供了这个机会

只需在 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:

一个优秀的自由职业者,应该有对需求敏感和精准需求捕获的能力,而huntsbot.com提供了这个机会

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:

一个优秀的自由职业者,应该有对需求敏感和精准需求捕获的能力,而huntsbot.com提供了这个机会

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

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

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

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

答9:

huntsbot.com洞察每一个产品背后的需求与收益,从而捕获灵感

仅对于主机名,使用:

window.location.hostname

答10:

huntsbot.com聚合了超过10+全球外包任务平台的外包需求,寻找外包任务与机会变的简单与高效。

这也将起作用:

var currentURL = window.location.href;

这给出了大多数人寻找的完整 URL。

答11:

huntsbot.com全球7大洲远程工作机会,探索不一样的工作方式

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

协议 « Web 浏览器通过遵循一些规则在 WebHosted 应用程序和 Web 客户端(浏览器)之间进行通信来使用 Internet 协议。 (http = 80,https (SSL) = 443,ftp = 21 等)

EX:使用默认端口号

//:/
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 );

https://i.stack.imgur.com/I79ER.png

带有 username:password 的身份验证 url,如果 usernaem/password 包含 @ 符号,如:

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

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

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

encodeURI()(与)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 (-_.!~*')
*/

原文链接:https://www.huntsbot.com/qa/eR2A/get-current-url-with-jquery?lang=zh_CN&from=csdn

huntsbot.com提供全网独家一站式外包任务、远程工作、创意产品分享与订阅服务!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值