原文地址:http://blog.sina.com.cn/s/blog_944b24ef0101epr5.html
一、给jQuery对象添加自定义方法
方法一、$.fn.
xxx
方法二、jQuery.fn.extend({
xxx:function(){
alert($(this).val());
}
});
方法一示例:
$.fn.setCursorPosition =
function(position){
if(
this.lengh ==
0)
return this;
return $(
this).setSelection(position, position);
}
$.fn.setSelection =
function(selectionStart, selectionEnd) {
if(
this.lengh ==
0)
return this;
input =
this[
0];
if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(
true);
range.moveEnd(
'character', selectionEnd);
range.moveStart(
'character', selectionStart);
range.
select();
}
else if (input.setSelectionRange) {
input.
focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
return this;
}
$.fn.focusEnd =
function(){
this.setCursorPosition(
this.val().
length);
}
方法二示例:
$.fn.extend({
setCursorPosition:
function(position){
if(
this.lengh ==
0)
return this;
return $(
this).setSelection(position, position);
},
setSelection:
function(selectionStart, selectionEnd) {
if(
this.lengh ==
0)
return this;
input =
this[
0];
if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(
true);
range.moveEnd(
'character', selectionEnd);
range.moveStart(
'character', selectionStart);
range.
select();
}
else if (input.setSelectionRange) {
input.
focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
return this;
},
focusEnd:
function(){
this.setCursorPosition(
this.val().
length);
}
});
以上定义都可如此调用:
$(
'.num').
click(
function(){
$(
'.num').focusEnd();
});
二、扩展jQuery类本身 为类添加新的方法
方法一、jQuery.extend(object);
方法二、jQuery.
xxx=function(){};
方法一示例:
$.extend({
add:
function(a,b){
return a+b;},
a:
'2 chi gege '
});
alert($.add(
3,
4));
//7
alert($.a);
//2 chi gege
方法二示例:
$.add2 =
function(a,b){
return a-b;
}
alert($.add2(
4,
3));
//1