JS常用代码片段集合
作者:admin 日期:2014-06-19
JS实现String#repeat
var a = new Array(10+1).join('-');
绑定函数的this指针(scope)
function bind(func, obj)
{
return function(){
func.apply(obj, arguments);
};
}
var obj = {
name : "WEB应用开发",
url : "http://www.zeroplace.cn"
};
var func = bind(function(param){
alert(this.name + " " + this.url + " " + param);
}, obj);
func("很不错的网站");
获取和设置COOKIE
function setCookie(key, value, path, domain, expires, secure)
{
var cookie = [];
cookie.push(key + "=" + escape(value || ""));
if (!value) {
expires = new Date(Date.now() - 1).toGMTString();
}
if (path) {
cookie.push("path=" + path);
}
if (domain) {
cookie.push("domain=" + domain);
}
if (expires) {
cookie.push("expires=" + expires);
}
if (secure) {
cookie.push("expires");
}
console.log(document.cookie = cookie.join(";"));
}
function getCookie(name)
{
var pattern = new RegExp(name + "=(.*?)(?:;|$)");
var arr = document.cookie.match(pattern);
if (arr) {
return arr[1];
} else {
return null;
}
}
JS时间格式化
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
//调用:
var time1 = new Date().Format("yyyy-MM-dd");
var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");
JS克隆对象
function clone(obj) {
var o;
switch (typeof obj) {
case "undefined':
break;
case 'string':
o = obj + '';
break;
case 'number':
o = obj - 0;
break;
case 'boolean':
o = obj;
break;
case 'object':
if (obj === null) {
o = null;
} else {
if (obj instanceof Array) {
o = [];
for (var i = 0, len = obj.length; i < len; i++) {
o.push(clone(obj[i]));
}
} else {
o = {};
for (var k in obj) {
o[k] = clone(obj[k]);
}
}
}
break;
default:
o = obj;
break;
}
return o;
}
js加入收藏
这个代码是支持了IE和火狐,对于其它浏览器就直接弹出一个框提示用户手动收藏
function AddFavorite(title, url) {
try {
window.external.addFavorite(url, title)
} catch(e) {
try {
window.sidebar.addPanel(title, url, "")
} catch(e) {
alert("抱歉,您所使用的浏览器无法完成此操作。\n\n加入收藏失败,请使用Ctrl+D进行添加")
}
}
}
-------------------------
待续, 欢迎大家留言补充
评论: 0 | 查看次数: 6533
订阅
另类PHP一句话小马
PHPCMS乱解读之 PHPCMS如何生成模型表单

文章来自:
Tags: