jQuery内核,以及自定义each和size方法

来源:互联网 发布:一起看软件神器 编辑:程序博客网 时间:2024/05/22 00:33
jQuery的内核;
  (function( window, undefined ) {
       //这就是jQuery的原型
       var jQuery = function( selector, context ) {
           return new jQuery.fn.init( selector, context );
       }

       //利用jQuery选择器产生的对象就是jQuery产生的对象,所以利用选择器产生的对象才拥有了jQuery中prototype中的内容
       jQuery.fn = jQuery.prototype = {
            ready:function(){},
            each:function(){},
            size:function(){}
       }

       以下这些都是相同的

       //window.jQuery.prototype=window.jQuery.fn=window.$.prototype=window.$.fn

         =jQuery.prototype=jQuery.fn=$.prototype=$.fn

       jquery最后将jQuery对象赋值到window对象的属性中,提供给外界使用

       window.jQuery = window.$ = jQuery;
       把加在jQuery对象上的方法或者加jQuery.prototype上的方法称为jQuery的插件开发
       jQuery.a = function(){

       }
       jQuery.prototype.b = function(){}

       总结:如果该方法与页面上的元素没有关系,该方法就为jQuery中全局的插件方法
                  如果该方法与页面上的元素有关系,则方法就必须加在jQuery的prototype上

  })(window);



自定义jquery中的each方法和size方法

(function($){/** * 这个方法将来是由jquery利用选择器产生的对象来调用的  * callBack是回调函数,因为不晓得将来要对数组中的每个元素进行什么操作,所以这里将每个元素都传给回调函数,有几个元素,回调函数就被调用几次 */$.fn.a = function(callBack){var arry = $(this);//表示jquery利用选择器产生的对象(这里是要数组)for(var i=0;i<arry.length;i++){//由回调函数去决定怎么处理数组中的每个元素callBack.apply(arry[i]);}},$.prototype.b = function(){return $(this).length;};})($);$().ready(function(){$("input").a(function(){//由于回调函数是由数组中的每个元素来进行调用的,所以$(this)表示当前遍历对象alert($(this).attr("value"));});alert($("input").b());});

html

<body>    <input type="button" value="button1">    <input type="button" value="button2"></body>


原创粉丝点击