jQuery 获取URL, 拆分URL结构

来源:互联网 发布:gx developer编程手册 编辑:程序博客网 时间:2024/05/29 13:48

jQuery 获取URL, 拆分URL结构

在做网站的时候,经常会遇到对url进行分类,不同的url显示不同的布局或者让用户很清晰的知道当前在哪个页面。如果在每个不同页面写方法,工程量大,代码重复率太高,也不便于修改。如果有很多页面都有相似的结构,比如header,footer等等,我们可以使用一个模板页面来写好共同的结构。

下面写下jQuery对于URL的获取和拆分。

先介绍下window location的属性

window.location
属性          描述
hash         设置或获取 href 属性中在井号“#”后面的分段。
host         设置或获取 location 或 URL 的 hostname 和 port 号码。
hostname    设置或获取 location 或 URL 的主机名称部分。
href          设置或获取整个 URL 为字符串。
pathname    设置或获取对象指定的文件名或路径。
port          设置或获取与 URL 关联的端口号码。
protocol      设置或获取 URL 的协议部分。
search       设置或获取 href 属性中跟在问号后面的部分。

1.设置或获取整个 URL 为字符串

window.location.href
eg: URL: http://localhost:8000/test/index.html
console.log(window.location.href);
输出结果:http://localhost:8000/test/index.html

2.设置或获取对象指定的文件名或路径

window.location.pathname
eg: URL: http://localhost:8000/demo/job
console.log(window.location.pathname);
输出结果:/demo/job

eg2: URL: http://localhost:8000/topic/index?topicId=361

console.log(window.location.pathname);

输出结果:/topic/index

3. 设置或获取与 URL 关联的端口号码

window.location.port
eg: URL: http//localhost:8000/test/
console.log(window.location.pathname);
输出结果:8000

4. 设置或获取 URL 的协议部分

window.location.protocol
eg: https://test.demo.com
console.log(window.location.protocol);
输出结果:https

5. 设置或获取 href 属性中在井号“#”后面的分段

window.location.hash

6. 设置或获取 location 或 URL 的 hostname 和 port 号码

window.location.host
eg: http://localhost:8000/topic/index?topicId=253
console.log(window.location.protocol);
输出结果:localhost:8000

7. 设置或获取 href 属性中跟在问号后面的部分

window.location.search
eg: http://localhost:8000/topic/index?topicId=253
console.log(window.location.search);
输出结果: ?topicId=253
0 0