下面我们举例一个URL,然后获得它的各个组成部分。
http://www.baidu.com/abc?id=100
window.location.href
可以获得整个URL字符串(在浏览器中就是完整的地址栏)。
var test = window.location.href;
alert(test);
程序返回 http://www.baidu.com/abc?id=100
window.location.protocol
可以获得 URL 的协议部分
var test = window.location.protocol;
alert(test);
程序返回 http:
window.location.host
可以获得 URL 的主机部分
var test = window.location.host;
alert(test);
程序返回 www.baidu.com
window.location.port
可以获得 URL 的端口部分
var test = window.location.port;
alert(test);
如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符。
window.location.pathname
获得 URL 的路径部分(就是文件地址)
var test = window.location.pathname;
alert(test);
window.location.search
获得查询(参数)部分,除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值。
var test = window.location.search;
alert(test);
window.location.hash
获得锚点。
var test = window.location.hash;
alert(test);