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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.duanlonglong.com/qdjy/262.html