码迷,mamicode.com
首页 > Web开发 > 详细

js url参数操作插件

时间:2014-09-17 18:20:32      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:http   io   ar   for   2014   sp   cti   log   on   

// 当前页面url参数操作插件
// Author:Bean
// Date:2014/09/17
;
(function(window, document) {

var UrlParas = function(url) {
return UrlParas.fn.init(url);
}
UrlParas.VERSION = ‘1.0.0‘;
UrlParas.fn = UrlParas.prototype = {

url: "",
pathname: "",
paras: "",
init: function(url) {
this.url = url;
this.pathname = url.split("?")[0];
this.paras = this.get();
return this;
},

//以object类型返回url参数及其取值
get: function(option) {
var paraStr, paras,
url = this.url;
if (url) {
paraStr = url.split("?")[1];
if (paraStr) {
paras = {};
paraStr = paraStr.split("&");
for (var n in paraStr) {
var name = paraStr[n].split("=")[0];
var value = paraStr[n].split("=")[1];
paras[name] = value;
}
} else {
return {};
}
if (!option) {
return paras;
} else {
return paras[option] ? paras[option] : "";
}


}
},

//重设url参数取值,若无此参数则进行创建,若参数赋值为null则进行删除
set: function(option) {
var i, name, val;
if (arguments.length == 2) {
name = arguments[0];
val = arguments[1];
option = {
name: val
};
}
if ("string" === typeof option) {
this.paras[option] = "";
} else if ("object" === typeof option) {
for (i in option) {
if (option[i] === null) {
delete this.paras[i];
} else {
this.paras[i] = option[i];
}
}
} else {

}
return this.build();
},

//删除url中指定参数返回新url
remove: function(option) {
var i;
if ("string" === typeof option) {
option = option.split(",");
for (i in option) {
delete this.paras[option[i]]
}

}
return this.build();
},

//根据url和处理过的paras重新构件url
build: function() {
var i,
newUrl = this.pathname + "?";

for (i in this.paras) {
newUrl += (i + "=" + this.paras[i] + "&");
}

return newUrl.substr(0, newUrl.length - 1);
}


}

UrlParas.fn.init.prototype = UrlParas.fn;

window.urlParas = UrlParas;

})(window, document);


//用法示例
testUrl = "http://127.0.0.1/test/urlParas.html?lang=2&tt=22";
console.log(urlParas(testUrl).get());
console.log(urlParas(testUrl).set("test"));
console.log(urlParas(testUrl).set("test", "bean"));
console.log(urlParas(testUrl).set({
"ajax": "ok",
"lang": null,
"test": null
}));
console.log(urlParas(testUrl).set({
zcsdf: "zcsdf",
lang: "zh-cn"
}));
console.log(urlParas(testUrl).remove("lang,tt"));
console.log(urlParas(testUrl).pathname);

// 输出结果
// Object {lang: "2", tt: "22"}
// http://127.0.0.1/test/urlParas.html?lang=2&tt=22&test=
// http://127.0.0.1/test/urlParas.html?lang=2&tt=22&name=bean
// http://127.0.0.1/test/urlParas.html?tt=22&ajax=ok
// http://127.0.0.1/test/urlParas.html?lang=zh-cn&tt=22&zcsdf=zcsdf
// http://127.0.0.1/test/urlParas.html
// http://127.0.0.1/test/urlParas.html

js url参数操作插件

标签:http   io   ar   for   2014   sp   cti   log   on   

原文地址:http://www.cnblogs.com/Beanzone/p/3977565.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!