ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[toc] ## 查看当前location对象 ``` console.log(location); ``` ![](https://box.kancloud.cn/53eca8fcbbfd976ca7e375661d94f6f1_338x291.png) ``` function showLoc() { var oLocation = window.location, aLog = ["Property (Typeof): Value", "window.location (" + (typeof oLocation) + "): " + oLocation ]; for (var sProp in oLocation){ aLog.push(sProp + " (" + (typeof oLocation[sProp]) + "): " + (oLocation[sProp] || "n/a")); } alert(aLog.join("\n")); } showLoc(); ``` ## location和location.href和location.assign() MDN文档中说`window.location`这货是个只读属性,但又说这货可以被赋值。。。 emmm...你别听它的 除此之外`window.location=`和`window.location.href=`和`window.location.assign()`是等价的 ### href支持hash 且如果赋的是一个hash值(比如`#123`),它会自动识别,并在原本的location地址末尾追加上(`原先的地址#123`) ## location.reload:强制从服务器重新加载当前页面 ``` window.location.reload(true); ``` ## location.replace ``` function reloadPageWithHash() { var initialPage = window.location.pathname; window.location.replace('http://example.com/#' + initialPage); } ``` ## location.search:向当前服务器地址发送query ![](https://box.kancloud.cn/c734e64bbca2af456680a153c779b245_538x128.png) ``` function sendData (sData) { window.location.search = sData; } ``` ### 封装一个query对象 ``` var oGetVars = {}; if (window.location.search.length > 1) { for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) { aItKey = aCouples[nKeyId].split("="); oGetVars[decodeURIComponent(aItKey[0])] = aItKey.length > 1 ? decodeURIComponent(aItKey[1]) : ""; } } // alert(oGetVars.yourVar); ``` 同样可以通过一个匿名构造函数来获取,这样只声明了一个全局变量。 ``` var oGetVars = new (function (sSearch) { if (sSearch.length > 1) { for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) { aItKey = aCouples[nKeyId].split("="); this[decodeURIComponent(aItKey[0])] = aItKey.length > 1 ? decodeURIComponent(aItKey[1]) : ""; } } })(window.location.search); // alert(oGetVars.yourVar); ``` ### 获取query对象中的键值 ``` function loadPageVar (sVar) { return decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")); } alert(loadPageVar("name")); ``` ### 更多请查看MDN case 8: ... [MDN](https://developer.mozilla.org/zh-CN/docs/Web/API/Window/location)