1、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
2、查詢字符串參數
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"}
3、位置修改
//假設初始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;
4、加載
location.assign("http://www.wrox.com");
location.href = "http://www.wrox.com";
location.replace("http://www.wrox.com/");
location.reload(); //從新加載(有可能從緩存中加載)
location.reload(true); //從新加載(從服務器從新加載)