标签:
函数用途:如标题,1. 从URL中解析出参数,2.重写URL中的参数值
如下代码所示,包含了测试。可以直接copy到浏览器中,输入测试地址:localhost:xxx?a=1&b=2&c=3 ,在console中运行查看结果:
// - test // - get from current location var url = document.location.href; // - extract param from url console.log(getUrlParam(url,"a") == "1"); console.log(getUrlParam(url,"b") == "2"); console.log(getUrlParam(url,"c") == "3"); // - rewrite url url = setUrlParam(url,"a",3); url = setUrlParam(url,"b",1); url = setUrlParam(url,"c",2); console.log(getUrlParam(url,"a") == "3"); console.log(getUrlParam(url,"b") == "1"); console.log(getUrlParam(url,"c") == "2"); // - helper functions function getUrlParam(location,name) { var url = location; var splitIndex = url.indexOf("?") + 1; var paramStr = url.substr(splitIndex, url.length); var arr = paramStr.split(‘&‘); for (var i = 0; i < arr.length; i++) { var kv = arr[i].split(‘=‘); if (kv[0] == name) { return kv[1]; } } return ""; } function setUrlParam(location,name, value) { var url = location; var splitIndex = url.indexOf("?") + 1; var paramStr = url.substr(splitIndex, url.length); var newUrl = url.substr(0, splitIndex); // - if exist , replace var arr = paramStr.split(‘&‘); for (var i = 0; i < arr.length; i++) { var kv = arr[i].split(‘=‘); if (kv[0] == name) { newUrl += kv[0] + "=" + value; } else { if (kv[1] != undefined) { newUrl += kv[0] + "=" + kv[1]; } } if (i != arr.length - 1) { newUrl += "&"; } } // - if new, add if (newUrl.indexOf(name) < 0) { newUrl += splitIndex == 0 ? "?" + name + "=" + value : "&" + name + "=" + value; } return newUrl; }IE中运行结果:
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/46336857