1.2.7.3.深入瞭解原始碼:jQeury(三)
方法鏈結 (method chaining)
//取得class是people的ul中的li
var q = $("ul.people li").addClass("newclass").removeClass("people")
//印出jQuery.fn.init[3]
console.log(q)
原始碼
this會指向jQuery物件
addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + curValue + " " ).replace( rclass, " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( curValue !== finalValue ) { jQuery.attr( elem, "class", finalValue ); } } } } return this; },
Last updated
Was this helpful?