一、location對象
http://localhost:8881/javascript/BOM/window.html?name=bob&age=123
console.log('獵取hash:', window.location.hash);
// 獵取服務器稱號和端口號host: localhost:8881
console.log('獵取服務器稱號和端口號host:', window.location.host);
// 獵取服務器稱號和端口號host: localhost:8881
console.log('獵取不帶端口號的服務器稱號hostname:', window.location.hostname);
// 獵取不帶端口號的服務器稱號hostname: localhost
console.log('獵取全部url href:', window.location.href);
// 獵取全部url href: http://localhost:8881/javascript/BOM/window.html?name=bob&age=123
console.log('返回URL中的目次和(或)文件名pathname', window.location.pathname);
// 返回URL中的目次和(或)文件名pathname /javascript/BOM/window.html
console.log('返回url的端口號', window.location.port);
// 返回url的端口號 8881
console.log('返回url的協定 protocol', window.location.protocol);
// 返回url的協定 protocol http:
console.log('返回URL的查詢字符串 這個字符串以問號開首 search', window.location.search);
// 返回URL的查詢字符串 這個字符串以問號開首 search ?name=bob&age=123
二、查詢字符串參數
function getQueryStringArgs() {
//獲得查詢字符串並去掉開首的問號
var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
//保留數據的對象
args = {},
//獲得每一項
items = qs.length ? qs.split("&") : [],
item = null,
name = null,
value = null,
//在for輪迴中運用
i = 0,
len = items.length;
//逐一將每一項添加到args對象中
for (i = 0; i < len; i++) {
item = items[i].split("=");
name = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
if (name.length) {
args[name] = value;
}
}
return args;
}
console.log(getQueryStringArgs()); // {name: "bob", age: "123"}
三、位置修正
//假定初始URL為http://www.wrox.com/WileyCDA/
//將URL修正為"http://www.wrox.com/WileyCDA/#section1"
location.hash = "#section1";
//將URL修正為"http://www.wrox.com/WileyCDA/?q=javascript"
location.search = "?q=javascript";
//將URL修正為"http://www.yahoo.com/WileyCDA/"
location.hostname = "www.yahoo.com";
//將URL修正為"http://www.yahoo.com/mydir/"
location.pathname = "mydir";
//將URL修正為"http://www.yahoo.com:8080/WileyCDA/"
location.port = 8080;
四、加載
location.assign("http://www.wrox.com");
location.href = "http://www.wrox.com";
location.replace("http://www.wrox.com/");
location.reload(); //從新加載(有能夠從緩存中加載)
location.reload(true); //從新加載(從服務器從新加載)