使用JavaScript擷取地址欄參數的方法

來源:互聯網
上載者:User

 代碼如下:


/**
 *  擷取地址欄參數
 *
 * @example GetUrlString('id')
 *
 * @desc    調用時加上判斷,保證程式不會出錯
 *             var myurl = GetUrlString('id');
 *             if (myurl != null && myurl.toString().length > 1) {
 *                  alert(GetUrlString("id")); 
 *             }
 *
 * @param String  param 要擷取地址欄中的參數名
 * @return String Value
 * @type String
 *
 * @name GetUrlString()
 *
 */
function GetUrlString(param) {
    var sValue = location.search.match(new RegExp("[?&]" + m + "=([^&]*)(&?)", "i"));
    return sValue ? decodeURI(sValue[1]) : decodeURI(sValue);
}

 

調用的時候統一做這樣的判斷,避免你沒有傳參數的話,比如你的地址是 abc.html 後面沒有參數,那強行輸出調用結果有的時候會報錯

 

代碼如下:
window.onload = function() {   
    var myurl = GetParm("id");
    if (myurl != null && myurl.toString().length > 1) {
        alert(GetParm("id"));
    }
}

 

這樣就不會報錯了!

注釋:ECMAScript v3 已從標準中刪除了 unescape() 函數,並反對使用它,因此應該用 decodeURI() 和 decodeURIComponent() 取而代之。

小夥伴們是否理解了如何使用JavaScript擷取地址欄參數了呢,有疑問的話就留言吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.