組合模式 描述了一組對象可像單個對象一樣的對待。
這允許我們能統(tǒng)一的處理單個對象或多個對象。這意味著無論是一個對象還是一千個對象我們都能以同樣的行為來處理。
在Jquery中,當(dāng)我們在一個節(jié)點(diǎn)或多個節(jié)點(diǎn)上應(yīng)用方法時,我們都能以相同的方式來選擇并返回JQuery對象。
下面這個演示我們將使用Jquery的選擇器。對單一元素(比如擁有唯一ID的元素)或擁有相同標(biāo)簽或Class的一組元素添加名為active的class,對待它們使用上并無不同:
// 單一節(jié)點(diǎn)
$( "#singleItem" ).addClass( "active" );
$( "#container" ).addClass( "active" );
// 一組節(jié)點(diǎn)
$( "div" ).addClass( "active" );
$( ".item" ).addClass( "active" );
$( "input" ).addClass( "active" );
JQuery的addClass()實(shí)現(xiàn)中直接使用原生的for循環(huán)、Jquery的JQuery.each()、Jquery.fn.each來迭代一個集合以達(dá)到能同時處理一個或一組元素的目的。請看下面的例子:
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
}
更多建議: