DIV CSS 佈局教程網

jQuery 源碼解讀:addClass() 方法實現分析
編輯:JavaScript綜合知識     

addClass() 是我們最常用的 DOM 操作方法之一,但它的源碼同時處理了字符串參數、函數參數、多類名、去重和鏈式調用五件事,邏輯密度遠比表面看起來高。

源碼結構

jQuery.fn.extend({
  addClass: function( value ) {
    var classes, elem, cur, clazz, j, finalValue,
      i = 0,
      len = this.length,
      // 僅當 value 是非空字符串時 proceed 才為真
      proceed = typeof value === "string" && value;

    // 情況一:傳入的是函數
    if ( jQuery.isFunction( value ) ) {
      return this.each(function( j ) {
        // 以每個 DOM 元素為上下文調用,返回值再次遞歸進入 addClass
        jQuery( this ).addClass( value.call( this, j, this.className ) );
      });
    }

    // 情況二:傳入的是非空字符串
    if ( proceed ) {
      // /S+/g 全局匹配非空白字符,得到 ["show", "bd1"]
      classes = ( value || "" ).match( rnotwhite ) || [];

      for ( ; i < len; i++ ) {
        elem = this[ i ];
        // 已有 className 時前後補空格並規範化空白字符,否則給一個空格
        cur = elem.nodeType === 1 && ( elem.className ?
              ( " " + elem.className + " " ).replace( rclass, " " ) : " ");

        if ( cur ) {
          j = 0;
          // 逐個判斷是否已存在,不存在才追加
          while ( (clazz = classes[j++]) ) {
            if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
              cur += clazz + " ";
            }
          }
          // 去掉首尾空格,並避免寫入重複值引發不必要的渲染
          finalValue = jQuery.trim( cur );
          if ( elem.className !== finalValue ) {
            elem.className = finalValue;
          }
        }
      }
    }
    return this;
  }
});

幾處設計細節

proceed 的巧妙之處。源碼沒有直接寫 typeof value === "string" 的布爾判斷,而是寫 typeof value === "string" && value。利用 && 的返回值規則,非字符串類型最終都會得到一個假值,字符串則直接得到字符串本身,一個表達式同時完成了「類型檢查」和「取值」。

函數參數支持。當傳入函數時,jQuery 會以每個元素為 this、傳入索引與當前 className 調用它,再把返回值遞歸交回 addClass。這讓 .addClass(function(i, cls){ return ... }) 這類按元素差異化處理的寫法成為可能。

去重與「寫入前比對」。循環裡用 cur.indexOf(" " + clazz + " ") < 0 保證不重複添加;最後還多了一層 elem.className !== finalValue 判斷,內容沒變就不寫入。這一步能避免觸發瀏覽器不必要的樣式重算,是典型的老派性能優化手法。

返回 this。始終回傳 jQuery 對象,鏈式調用由此成立。

讀完這段源碼,再回頭看自己寫的 classList.add(),大概能理解當年為什麼需要這麼多代碼——那時並沒有原生的類名操作 API 可用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved