jQuery扩展两类函数(对象调用,静态调用)

作者:zccst

先看小例子:

$(function(){
    //扩展方式1-通过对新调用
    $.fn.each1=function(){
        console.log("hehehehe$.fn.func");
    }
    $.fn.extend({
        "each2":function(){
            console.log("second method!,$.fn.extend(each2:function(){})");
        }
    });
    //扩展方式2-静态调用
    $.extend({
        "each3":function(){
            console.log("hahah,$.extend(each3:function(){})");
        }
    });
    $("button").click(function(){
        console.log($(".name").val());
        $(this).each1();//通过对象调用
        $(this).each2();//通过对象调用
        $.each3();//扩展方式2-静态调用
    });
});


名字:<input class="name" type="text" />
<button>提交</button>

 

 

 

方法一:对象调用
   jQuery.fn.setApDiv=function () {
        //apDiv浮动层显示位置居中控制
        var wheight=$(window).height();
        var wwidth=$(window).width();
        var apHeight=wheight-$("#apDiv").height();
        var apWidth=wwidth-$("#apDiv").width();
        $("#apDiv").css("top",apHeight/2);
        $("#apDiv").css("left",apWidth/2);
    }

调用方法:$("#apDiv").setApDiv();


--------------------------------------------------------------------------------
方法二:静态调用
      //jQuery 应用扩展
      jQuery.extend({
              // 设置 apDiv
            setApDiv:function () {
            //apDiv浮动层显示位置居中控制
            var wheight=$(window).height();
            var wwidth=$(window).width();
            var apHeight=wheight-$("#apDiv").height();
            var apWidth=wwidth-$("#apDiv").width();
            $("#apDiv").css("top",apHeight/2);
            $("#apDiv").css("left",apWidth/2);
            }
      });
调用方法:$.setApDiv();

总结 一种如$.extend({'aa':function(){}}),这种调用时就是这样$.aa(),另一种如$.fn.extend({'aa':function(){}}),这种调用时就得这样,$(this).aa()

--------------------------------------------------------------------------------
方法三:
      
     $.postJSON = function(url, data, callback) {
  $.post(url, data, callback, "json");
 };
调用方法:$.postJSON('/post/getsecurejsonpost',{}, function(data) {});

posted @ 2014-05-14 18:35  走走停停走走  Views(309)  Comments(0Edit  收藏  举报