其中的一些代码段是从jQuery1.4.2才开始支持的做法,另一些则是真正有用的函数或方法,他们能够帮助你又快又好地把事情完成。
- 如何限制“Text-Area”域中的字符的个数:
jQuery.fn.maxLength = function(max){
return this.each(function(){
var type = this.tagName.toLowerCase();
var inputType = this.type? this.type.toLowerCase() : null;
if(type == "input" && inputType == "text" || inputType == "password"){
//Apply the standard maxLength
this.maxLength = max;
} else if(type == "textarea"){
this.onkeypress = function(e){
var ob = e || event;
var keyCode = ob.keyCode;
var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
};
this.onkeyup = function(){
if(this.value.length > max){
this.value = this.value.substring(0,max);
}
};
}
});
};
//用法
$('#mytextarea').maxLength(500);
如何把一个元素放在屏幕的中心位置:
jQuery.fn.center = function () {
return this.each(function(){
$(this).css({
position:'absolute',
top, ( $(window).height() - this.height() ) / 2 + $(window).scrollTop() + 'px',
left, ( $(window).width() - this.width() ) / 2 + $(window).scrollLeft() + 'px'
});
});
}
//这样来使用上面的函数:
$(element).center();
如何把有着某个特定名称的所有元素的值都放到一个数组中:
Array push
var arrInputValues = new Array();
$("input[name='xxx']").each(function(){
arrInputValues.push($(this).val());
});
使用Firebug和Firefox来记录jQuery事件日志:
// 允许链式日志记录
jQuery.log = jQuery.fn.log = function (msg) {
if (console){
console.log("%s: %o", msg, this);
}
return this;
};
// 用法:
$('#someDiv').hide().log('div hidden').addClass('someClass');
如何强制在弹出窗口中打开链接:
$('a.popup').live('click', function(){
var newwindow = window.open($(this).attr('href'),'','height=200,width=150');
if (window.focus) {
newwindow.focus();
}
return false;
});
如何强制在新的选项卡中打开链接:
$('a.newTab').live('click', function(){
var newwindow=window.open(this.href);
$(this).target = "_blank";
return false;
});
获取鼠标悬浮点,x和Y的坐标值
$(document).ready(function() {
$(document).mousemove(function(e){
$(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);
});
});
如何使用String的验证方法:
$.extend(String.prototype, {
isPositiveInteger:function(){
return (new RegExp(/^[1-9]\d*$/).test(this));
},
isInteger:function(){
return (new RegExp(/^\d+$/).test(this));
},
isNumber: function(value, element) {
return (new RegExp(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/).test(this));
},
trim:function(){
return this.replace(/(^\s*)|(\s*$)|\r|\n/g, "");
},
trans:function() {
return this.replace(/</g, '<').replace(/>/g,'>').replace(/"/g, '"');
},
replaceAll:function(os, ns) {
return this.replace(new RegExp(os,"gm"),ns);
},
skipChar:function(ch) {
if (!this || this.length===0) {return '';}
if (this.charAt(0)===ch) {return this.substring(1).skipChar(ch);}
return this;
},
isValidPwd:function() {
return (new RegExp(/^([_]|[a-zA-Z0-9]){6,32}$/).test(this));
},
isValidMail:function(){
return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(this.trim()));
},
isSpaces:function() {
for(var i=0; i < this.length; i+=1) {
var ch = this.charAt(i);
if (ch!=' '&& ch!="\n" && ch!="\t" && ch!="\r") {return false;}
}
return true;
},
isPhone:function() {
return (new RegExp(/(^([0-9]{3,4}[-])?\d{3,8}(-\d{1,6})?$)|(^\([0-9]{3,4}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/).test(this));
},
isUrl:function(){
return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this));
},
isExternalUrl:function(){
return this.isUrl() && this.indexOf("://"+document.domain) == -1;
}
});
如何规范化写jQuery插件:
(function($){
$.fn.extend({
pluginOne: function(){
return this.each(function(){
// my code
});
},
pluginTwo: function(){
return this.each(function(){
// my code
});
}
});
})(jQuery);
如何检查cookie是否启用
var dt = new Date();
dt.setSeconds(dt.getSeconds() + 60);
document.cookie = "cookietest=1; expires=" + dt.toGMTString();
var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
if(!cookiesEnabled) {
//没有启用cookie
}
如何让cookie过期:
var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });
如何使用一个可点击的链接来替换页面中任何的URL:
$.fn.replaceUrl = function() {
var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
return this.each(function() {
$(this).html(
$(this).html().replace(regexp,'<a href="$1">$1</a>')
);
});
}
//用法
$('p').replaceUrl();