JavaScript 修改地址欄指定參數

假如當前地址欄鏈接爲:https://test.com/?type=students&page=3

//定義替換參數的方法
function changeURLArg(url,arg,arg_val){ 
    var pattern=arg+'=([^&]*)'; 
    var replaceText=arg+'='+arg_val; 
    if(url.match(pattern)){ 
        var tmp='/('+ arg+'=)([^&]*)/gi'; 
        tmp=url.replace(eval(tmp),replaceText); 
        return tmp; 
    }else{ 
        if(url.match('[\?]')){ 
            return url+'&'+replaceText; 
        }else{ 
            return url+'?'+replaceText; 
        } 
    } 
    return url+'\n'+arg+'\n'+arg_val; 
}

var thisurl=window.location.href;   //https://test.com/?type=students&page=3
var newurl=changeURLArg(thisurl,'page','10');
alert(newurl);   //https://test.com/?type=students&page=10
var newurl2=changeURLArg(thisurl,'type','teachers');
alert(newurl2);   //https://test.com/?type=teachers&page=3

原文鏈接:https://tiicle.com/items/341/javascript-to-modify-the-address-bar-specified-parameters
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章