加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

给jquery对象添加自定义方法和扩展jquery类

(2014-06-23 20:52:21)
标签:

jquery

分类: jquery
  

一、给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

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有