使用js jquery分別獲取地址欄參數值


使用JS獲取地址欄參數

方法一:

function GetQueryString(name) {
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}

調用方法console.log(GetQueryString("參數名"));

方法二:

    /** 
  * 獲取指定URL的參數值 
  * @param url  指定的URL地址 
  * @param name 參數名稱 
  * @return 參數值 
  */  
 function getUrlParam(url,name) {  
     var pattern = new RegExp("[?&]"+name+"\=([^&]+)", "g");  
     var matcher = pattern.exec(url);  
     var items = null;  
     if(null != matcher){  
             try{  
                    items = decodeURIComponent(decodeURIComponent(matcher[1]));  
             }catch(e){  
                     try{  
                             items = decodeURIComponent(matcher[1]);  
                     }catch(e){  
                             items = matcher[1];  
                     }  
             }  
     }  
     return items;  
}  

調用方法console.log(getUrlParam(document.href,"參數名"));

使用jQuery獲取地址欄參數

使用下面的方式為jquery擴展一個方法來獲取url參數

(function ($) {
    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
})(jQuery);

調用方法console.log($.getUrlParam(參數名));

注意:javascript對參數編碼解碼方法要一致
escape()   unescape()

encodeURI()   decodeURI() 

encodeURIComponent()    decodeURIComponent()


免責聲明!

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



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