【js基礎】之BOM操做

1.知識點

  • navigator (navigator.userAgent)
  • screen (screen.width / screen.heigght)
  • location
  • history (history.back() / history.forward())
//示例
https://segmentfault.com/search?q=web#mid=100

//整個url
location.href
"https://segmentfault.com/search?q=web#mid=100"

//協議
location.protocol
"https:"

//域名
location.host
"segmentfault.com"

//路徑
location.pathname
"/search"

//參數
location.search
"?q=web"

//哈希
location.hash
"#mid=100"

2.檢驗瀏覽器的類型

navigator.userAgentweb

var ua = navigator.userAgent;
var isChrome = ua.indexOf('Chrome');
console.log(isChrome );

3.解析url

  1. 手動解析
function getQueryStringArgs(url){
        url = url == null ? window.location.href : url;
        var qs = url.substring(url.lastIndexOf("?") + 1);
        var args = {};
        var items = qs.length > 0 ? qs.split('&') : [];
        var item = null;
        var name = null;
        var value = null;
        for(var i=0; i<items.length; i++){
            item = items[i].split("=");
            //用decodeURIComponent()分別解碼name 和value(由於查詢字符串應該是被編碼過的)。
            name = decodeURIComponent(item[0]);
            value = decodeURIComponent(item[1]);

            if(name.length){
                args[name] = value;
            }
        }

        return args;
    }
console.log(getQueryStringArgs('https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=12306%E7%81%AB%E8%BD%A6%E7%A5%A8%E7%BD%91%E4%B8%8A%E8%AE%A2%E7%A5%A8%E5%AE%98%E7%BD%91'));
    // Object {tn: "monline_3_dg", ie: "utf-8", wd: "12306火車票網上訂票官網"}
  1. 使用正則
function getQueryObject(url) {
        url = url == null ? window.location.href : url;
        var search = url.substring(url.lastIndexOf("?") + 1);
        var obj = {};
        var reg = /([^?&=]+)=([^?&=]*)/g;
        // [^?&=]+表示:除了?、&、=以外的一到多個字符
        // [^?&=]*表示:除了?、&、=以外的0到多個字符(任意多個)
        search.replace(reg, function (rs, $1, $2) {
            var name = decodeURIComponent($1);
            var val = decodeURIComponent($2);
            val = String(val);
            obj[name] = val;
            return rs;
        });
        return obj;
    }
    console.log(getQueryObject('https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=12306%E7%81%AB%E8%BD%A6%E7%A5%A8%E7%BD%91%E4%B8%8A%E8%AE%A2%E7%A5%A8%E5%AE%98%E7%BD%91'));
    // Object {tn: "monline_3_dg", ie: "utf-8", wd: "12306火車票網上訂票官網"}
相關文章
相關標籤/搜索