jQuery学习笔记之.append()
将由参数指定的内容插入匹配元素集合中每个元素的尾部
这.append()
方法插入指定内容作为jQuery
集合中每个元素的最后一个子元素(为了插入这个内容作为第一个子元素,可以使用.prepend()
)
.append()
的参数类型
Html String
、Dom Element
、Text Node
、jQuery Object
、类型为Dom Element
或Text Node
的数组,也可以是function
如果参数是函数,这个函数接收两个参数,第一个参数是元素在集合中的下标,第二个参数是该元素的html值,在函数内部,this
指向集合中的当前元素,函数的返回类型可以是html 字符串、DOM 元素、文本节点 或 jQuery 对象,函数的返回值将插入到集合中的每一个元素尾部
选择一个页面上以存在的元素插入到其它元素中,则该元素将被移动到匹配元素集合中的最后一个元素,而匹配元素集合中的其他元素添加的都是这个元素的副本
function domManip( collection, args, callback, ignored ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = collection.length,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return collection.each( function( index ) {
var self = collection.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
domManip( self, args, callback, ignored );
} );
}
if ( l ) {
fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if ( first || ignored ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item
// instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( collection[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!dataPriv.access( node, "globalEval" ) &&
jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
DOMEval( node.textContent.replace( rcleanScript, "" ), doc );
}
}
}
}
}
}
return collection;
}
i !== iNoClone
用于判断当前元素是否为集合中的最后一个元素,当是集合中的最后一个元素时,直接将指定的内容添加到该元素中,若不是集合中的最后一个元素,则将指定内容的副本添加到该元素中