利用Javascript獲取當前頁的URL,這個問題起來好像很復雜,如果第一次去想這個問題,很多人估計又在琢磨到底又是哪個神一般的Javascript函數。
其實不是,Javascript獲取當前頁的URL的函數就是我們經常用來重定向的window.location.href。
比如如下函數:
- <script>
- var url=window.location.href;
- var loc = url.substring(url.lastIndexOf('/')+1, url.length);
- alert("url="+url+",loc="+loc);
- </script>
如果當前頁面的url為http://localhost:6666/myphp/mobile/pc1.php,那么其運行結果如下:
上面的函數同時展示如何獲取當前頁名稱的做法。
獲取利用window.location.href的變量獲取整個url之后,要哪一部分的地址,利用substring,indexof等字符串處理函數對獲取到的url進行處理,截取你想要的部分。
平時利用window.location.href做重定向,就是改變整個瀏覽器的url,
如果后面沒有賦值,這就成了獲取當前值的語句。
與document.getElementById("xx").value一樣,你能夠修改,就能夠獲取了。
刷新當前頁
window.location.href=window.location.href;
或者
window.location.href="當前URL",例如
window.location.href="http://www.hao123.com/indexnt.html";
PS:如果不考慮window.location.href,可以直接使用
window.location.reload();刷新