JavaScript獲取當前url路徑


1、假設當前頁完整地址是:http://localhost:61768/Home/Index?id=2&age=18

//獲取當前窗口的Url
var url = window.location.href;
//結果:http://localhost:61768/Home/Index?id=2&age=18

//獲取當前窗口的主機名
var host = window.location.host;
//結果:localhost:61768

//獲取當前窗口的端口
var port = window.location.port;
//結果:61768

//獲取當前窗口的路徑
var pathname = window.location.pathname;
//結果:/Home/Index

//獲取當前文檔的Url
var URL = document.URL;
//結果:http://localhost:61768/Home/Index?id=2&age=18

//獲取參數
var search = window.location.search;
//結果:?id=2&age=18

2、分隔 url 中的參數

var search = window.location.search;
var age = getSearchString('age', search); //結果:18
var id = getSearchString('id', search); //結果:2
//key(需要檢索的鍵) url(傳入的需要分割的url地址,例:?id=2&age=18)
function getSearchString(key, Url) {
    var str = Url;
    str = str.substring(1, str.length); // 獲取URL中?之后的字符(去掉第一位的問號)
    // 以&分隔字符串,獲得類似name=xiaoli這樣的元素數組
    var arr = str.split("&");
    var obj = new Object();

    // 將每一個數組元素以=分隔並賦給obj對象 
    for (var i = 0; i < arr.length; i++) {
        var tmp_arr = arr[i].split("=");
        obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
    }
    return obj[key];
}

3、跳出當前窗口

//跳出當前窗口,打開新窗口
window.open("http://www.baidu.com");

4、document與window

document默示的是一個文檔對象,window默示的是一個窗口對象,一個窗口下可以有多個文檔對象。

所以一個窗口下只有一個window.location.href,可能有多個document.URL、document.location.href

window.location.href 和 document.location.href 可以被賦值,然后跳轉到其它頁面,document.URL只能讀不能賦值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM