jquery源碼解析:jQuery對元素屬性的操作2

來源:互聯網
上載者:User

標籤:

這一課,我們將繼續講解jQuery對元素屬性操作的方法。

首先,我們先看一下這幾個方法是如何使用的:

$("#div1").addClass("box1 box2");     //給元素div的class屬性添加box1和box2

$("#div1").removeClass("box1");     //刪除元素div的class屬性值box1

$("#div1").toggleClass("box1");     //如果元素div的class屬性值中有box1,那麼就刪除box1。如果沒有,那麼就添加box1.

$("#div1").hasClass("box1");   //元素div的class屬性值是否有box1,如果有,就返回true,如果沒有,就返回false。

然後,我們來看一下源碼解析:

jQuery.fn.extend({

  ......

  addClass: function( value ) {
    var classes, elem, cur, clazz, j,
      i = 0,
        len = this.length,     //this指的是$("div")
          proceed = typeof value === "string" && value; //判斷傳入的參數是否是字串。我們在例子中,傳入的都是字串的形式,其實此方法,還可以傳入回調方法,比如:$("div").addClass(function(index){  return "box"+index; })  ,回調方法的傳回值,將會作為addClass的參數傳入。這段代碼就會在第一個div的class屬性中添加box0,在第二個div的class屬性中添加box1,以此類推。

    if ( jQuery.isFunction( value ) ) {   //傳入的參數是否是函數
      return this.each(function( j ) {
        jQuery( this ).addClass( value.call( this, j, this.className ) );  //回調方法的第一個參數是當前元素的index值,第二個參數是當前元素的class屬性值。
      });
    }

    if ( proceed ) {   //如果是字串
      classes = ( value || "" ).match( core_rnotwhite ) || [];  // core_rnotwhite = /\S+/g,把"box1 box2"轉換成[box1,box2]

      for ( ; i < len; i++ ) {  //迴圈元素
        elem = this[ i ];
        cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) :" ");   //如果是元素節點,就繼續進行判斷元素的class屬性值是否存在,rclass = /[\t\r\n\f]/g,\t是定位字元,\r是斷行符號,\n分行符號,\f是換頁。這些都是空白符,不是空格,我們需要把空白符替換成空格,以防元素的class屬性值之間用空白符隔開,而不是空格隔開的。比如:<div class="box1  box2">,這裡的box1和box2之間的\t就會替換成" "。

        if ( cur ) {   // " ",為真,""為假。
          j = 0;
          while ( (clazz = classes[j++]) ) {
            if ( cur.indexOf( " " + clazz + " " ) < 0 ) {   //判斷元素之前是否有此class屬性值,沒有才添加
              cur += clazz + " ";
            }
          }
          elem.className = jQuery.trim( cur );  //最後,去掉前後空格。

        }
      }
    }

    return this;
  },

  removeClass: function( value ) {
    var classes, elem, cur, clazz, j,
      i = 0,
        len = this.length,
          proceed = arguments.length === 0 || typeof value === "string" && value;  //&&優先順序高於||,所以先執行後面的&&操作。當不傳入什麼參數時,將會刪除此元素class所有的屬性值。比如:$("#div1").removeClass(),div1元素的class屬性值將會變成""。

    if ( jQuery.isFunction( value ) ) {   //如果傳入的是回調方法
      return this.each(function( j ) {
        jQuery( this ).removeClass( value.call( this, j, this.className ) );
      });
    }
    if ( proceed ) {   //如果傳入的是字串或者什麼都沒傳
      classes = ( value || "" ).match( core_rnotwhite ) || [];

      for ( ; i < len; i++ ) {
        elem = this[ i ];
        cur = elem.nodeType === 1 && ( elem.className ?( " " + elem.className + " " ).replace( rclass, " " ) :"");

        if ( cur ) {   //如果此元素有class屬性值,就進入if語句。
          j = 0;
          while ( (clazz = classes[j++]) ) {
            while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { //如果存在,就把此值刪除
              cur = cur.replace( " " + clazz + " ", " " );
            }
          }
          elem.className = value ? jQuery.trim( cur ) : "";  //如果沒傳入參數,就把元素的class屬性值賦為""。
        }
      }
    }

    return this;   //鏈式操作
  },

  toggleClass: function( value, stateVal ) {   //第二個參數,如果為true,就代表addClass,如果為false,就代表removeClass。
    var type = typeof value;

    if ( typeof stateVal === "boolean" && type === "string" ) {  //$("div").toggleClass("box1 box2",true);
      return stateVal ? this.addClass( value ) : this.removeClass( value );
    }

    if ( jQuery.isFunction( value ) ) {  
      return this.each(function( i ) {
        jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
      });
    }

    return this.each(function() {
      if ( type === "string" ) {
        var className,
          i = 0,
            self = jQuery( this ),
              classNames = value.match( core_rnotwhite ) || [];

        while ( (className = classNames[ i++ ]) ) {
          if ( self.hasClass( className ) ) {   //元素如果有此class屬性值,就刪除
            self.removeClass( className );
          } else {
            self.addClass( className );
          }
        }

      } else if ( type === core_strundefined || type === "boolean" ) {  //core_strundefined = undefined,如果是這種操作,$("#div1").toggleClass(false);或者$("#div1").toggleClass();就會進入else if語句。
        if ( this.className ) {   //如果此元素有class屬性值,就把屬性值存入jQuery緩衝系統中。
          data_priv.set( this, "__className__", this.className );
        }

        this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";       //假設div1有class="box1 box2",那麼執行$("#div1").toggleClass(false);或者$("#div1").toggleClass();將會把div1的class=""。之後,你再調用$("#div1").toggleClass(true);或者$("#div1").toggleClass();又會把dv1的class="box1 box2"。
      }
    });
  },

  hasClass: function( selector ) {
    var className = " " + selector + " ",
      i = 0,
        l = this.length;  
    for ( ; i < l; i++ ) {    //對所有匹配元素進行class的操作,也就是說$("div"),hasClass("box"),只要頁面上的任何一個div的class屬性值有box,就會返回true。
      if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
        return true;
      }
    }

    return false;
  },

  ......

});

下一課,將講解最後一個對屬性操作的方法val,因為此方法牽涉到valHooks,因此放到下一課講解。

 

 

 

加油!

jquery源碼解析:jQuery對元素屬性的操作2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.