jQuery08源码 (5140 , 6057) DOM操作 : 添加 删除 获取 包装 DOM筛选

Posted 672530440

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jQuery08源码 (5140 , 6057) DOM操作 : 添加 删除 获取 包装 DOM筛选相关的知识,希望对你有一定的参考价值。

jQuery.fn.extend({
//$(‘ul‘).find(‘li‘).css(‘background‘,‘red‘);
//$(‘ul‘).find( $(‘li‘) ).css(‘background‘,‘red‘);
    find: function( selector ) {
        var i,
            ret = [],
            self = this,
            len = self.length;
        if ( typeof selector !== "string" ) {//$(‘li‘)
            //jQuery( selector )是li集合,filter调用者是li,filter返回的是满足function条件的li,li.prevObject=所有li,
        //外层 this.pushStack返回满足条件的li,li.prevObject=所有ul,
            return this.pushStack( jQuery( selector ).filter(function() {
                for ( i = 0; i < len; i++ ) {
                    if ( jQuery.contains( self[ i ], this ) ) {//this是每一个li,是包含关系返回true
                        return true;
                    }
                }
            }) );
        }
        //$(‘ul‘).find(‘li‘).css(‘background‘,‘red‘);
        //‘li‘
        for ( i = 0; i < len; i++ ) {
            jQuery.find( selector, self[ i ], ret );//Sizzle
        }

        // Needed because $( selector, context ) becomes $( context ).find( selector ) , unique去重
        ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
        ret.selector = this.selector ? this.selector + " " + selector : selector;
        return ret;
    },
    /*
    <div class="box">div1<span class="box">span</span></div>
    <div>div2</div>
    <span class="box1">span1</span>
    <span class="box2">span2</span>
    <span class="box3">span3</span>
    $(‘div‘).has(‘span‘).css(‘border‘,‘1px red solid‘);
    */
    has: function( target ) {//target = "span"
    /*jQuery( target, this ):
    return ( context :div集合对象 || rootjQuery ).find( selector:"span" );Sizzle的find方法
    */
        var targets = jQuery( target, this ),//this是div集合,返回从div集合对象中找到的span对象<span class="box">span</span>
            l = targets.length;//1

        return this.filter(  function() {//this是div集合
            var i = 0;
            for ( ; i < l; i++ ) {
                if ( jQuery.contains( this, targets[i] ) ) {//this是每一个div
                    return true;
                }
            }
        }
/*
filter: function( f ) {  //这里没有函数体
    return this.pushStack( winnow(this, f || [], false) );//返回的是winnow(this, f || [], true)返回的结果并且结果.prevObject = 调用者。this是div集合
},
function winnow( elements, f, not ) {
        //把grep当成主体函数来看
        return jQuery.grep( elements, function( elem, i ) { //elements是div集合
            return !!f.call( elem, i, elem ) !== not;//elem是每一个div
        });//返回的是满足函数条件function也就是f的div集合
}
*/
        );
    },

    not: function( selector ) {
        //$(‘div‘).not(‘.box‘).css(‘border‘,‘1px red solid‘);
        /*
        pushStack: function( elems ) {
            var ret = jQuery.merge( this.constructor(), elems );
            ret.prevObject = this;
            return ret;  //返回的是满足条件的‘.div‘,这个‘.div‘的prevObject=$(‘div‘),用于回退
        }
        */
        //返回的是winnow(this, selector || [], true)返回的结果并且结果.prevObject = 调用者。
        return this.pushStack( winnow(this, selector || [], true) );
    },

    filter: function( selector ) {
        return this.pushStack( winnow(this, selector || [], false) );
    },

    is: function( selector ) {
        return !!winnow(
            this,

            // If this is a positional/relative selector, check membership in the returned set
            // so $("p:first").is("p:last") won‘t return true for a doc with two "p".
            typeof selector === "string" && rneedsContext.test( selector ) ?
                jQuery( selector ) :
                selector || [],
            false
        ).length;
    },

    //$(‘#div2‘).closest(‘.box‘)
    //$(‘#div2‘).closest(‘.box‘, $(‘body‘).get(0) )
    closest: function( selectors, context ) {
        var cur,
            i = 0,
            l = this.length,
            matched = [],
            pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ?
            //获取jqUERY对象
                jQuery( selectors, context || this.context ) :
                0;

        for ( ; i < l; i++ ) {
            for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
                // Always skip document fragments
                if ( cur.nodeType < 11 && (pos ?
                    pos.index(cur) > -1 :

                    // Don‘t pass non-elements to Sizzle
                    cur.nodeType === 1 &&
                        jQuery.find.matchesSelector(cur, selectors)) ) {

                    cur = matched.push( cur );//找到就push进来
                    break;//找到一个就跳出循环
                }
            }
        }
//入栈去重
        return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
    },

    // Determine the position of an element within
    // the matched set of elements
    index: function( elem ) {

//console.log( $(‘#div1‘).index() );//1,这个元素在所有兄弟节点的排名
        if ( !elem ) {
            //this.first() = this.eq(0);
            return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
        }

//$(‘#span1‘).index(‘span‘) ;//span1在所有span中的排名
        if ( typeof elem === "string" ) {
            return core_indexOf.call( jQuery( elem ), this[ 0 ] );
        }

        // $(‘span‘).index( $(‘#span1‘) ) );
        return core_indexOf.call( this,

            // If it receives a jQuery object, the first element is used
            elem.jquery ? elem[ 0 ] : elem
        );
    },

//$(‘div‘).add(‘span‘).css(‘border‘,‘1px red solid‘);//div span变红
    add: function( selector, context ) {
        var set = typeof selector === "string" ?
                jQuery( selector, context ) :
                jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
//this.get()是$(‘div‘)数组,set是‘span‘对象,合并成一个对象,
            all = jQuery.merge( this.get(), set );

        return this.pushStack( jQuery.unique(all) );
    },

//$(‘div‘).find(‘span‘).css(‘color‘,‘red‘).addBack(‘.box‘).css(‘border‘,‘1px red solid‘);//addBack回到栈的下一层,并且当前层和下一层进行操作。
    addBack: function( selector ) {
//this是span,this.prevObject是div,
        return this.add( selector == null ?
            this.prevObject : this.prevObject.filter(selector)
        );
    }
});

function sibling( cur, dir ) {
    while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}

    return cur;
}

//节点的获取
jQuery.each({
    parent: function( elem ) {//elem是每一个调用者div
        var parent = elem.parentNode;
        return parent && parent.nodeType !== 11 ? parent : null;
    },
    parents: function( elem ) {
        return jQuery.dir( elem, "parentNode" );
    },
    parentsUntil: function( elem, i, until ) {
        return jQuery.dir( elem, "parentNode", until );
    },
    next: function( elem ) {
        return sibling( elem, "nextSibling" );
    },
    prev: function( elem ) {
        return sibling( elem, "previousSibling" );
    },
    nextAll: function( elem ) {
        return jQuery.dir( elem, "nextSibling" );
    },
    prevAll: function( elem ) {
        return jQuery.dir( elem, "previousSibling" );
    },
    nextUntil: function( elem, i, until ) {
        return jQuery.dir( elem, "nextSibling", until );
    },
    prevUntil: function( elem, i, until ) {
        return jQuery.dir( elem, "previousSibling", until );
    },
    siblings: function( elem ) {
        return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
    },
    children: function( elem ) {
        return jQuery.sibling( elem.firstChild );
    },
    contents: function( elem ) {//elem每一个div
        return elem.contentDocument || jQuery.merge( [], elem.childNodes );
    }
}, function( name, fn ) {
    //jQuery.fn[ name ]是对jQuery.prototype对象的方法扩展
    /*
    map: function( elems, callback, arg ) {
        if (   callback( elems[ i ], i, arg )   != null ) {
            ret[ ret.length ] =  callback( elems[ i ], i, arg );//末尾追加
        }
        return ret;
    }
    $(‘div‘).parentsUntil(‘body‘,‘div‘), until, selector是‘body‘,‘div‘,与上面parentsUntil定义的无关,
    $(‘span‘).parents(‘body‘)
    */
    jQuery.fn[ name ] = function( until, selector ) {
        var matched = jQuery.map( this, fn, until );//this是div集合,返回fn(this[i],i,until)结果的集合
//具体操作都是在这里,真正实现是fn函数里面
        if ( name.slice( -5 ) !== "Until" ) {
            selector = until;//seletor=‘body‘
        }

        if ( selector && typeof selector === "string" ) {
            matched = jQuery.filter( selector, matched );
        }

        if ( this.length > 1 ) {
            /*
            guaranteedUnique = {
                children: true,
                contents: true,
                next: true,
                prev: true
            };
            */
            if ( !guaranteedUnique[ name ] ) {//在json里面
                jQuery.unique( matched );//去重
            }

            // Reverse order for parents* and prev-derivatives
            if ( rparentsprev.test( name ) ) {
                matched.reverse();
            }
        }

        return this.pushStack( matched );
    };
});

jQuery.extend({
    // jQuery.filter( ‘.box1‘, $(‘div‘),true )   div中class有box1的
    filter: function( expr, elems, not ) {
        var elem = elems[ 0 ];

        if ( not ) {
            expr = ":not(" + expr + ")"; // :not(.box1)
        }

        return elems.length === 1 && elem.nodeType === 1 ?
        //Sizzle完成
            jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
            jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
                return elem.nodeType === 1;
            }));
    },

    dir: function( elem, dir, until ) {
        var matched = [],
            truncate = until !== undefined;

        while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
            if ( elem.nodeType === 1 ) {
                if ( truncate && jQuery( elem ).is( until ) ) {
                    break;
                }
                matched.push( elem );
            }
        }
        return matched;
    },

    sibling: function( n, elem ) {
        var matched = [];

        for ( ; n; n = n.nextSibling ) {
            if ( n.nodeType === 1 && n !== elem ) {
                matched.push( n );
            }
        }

        return matched;
    }
});


//winnow($(‘div‘), ‘.box1‘ || [], true)  div中class有box1的
function winnow( elements, qualifier, not ) {//返回的是满足函数条件的elements元素集合
    /*
    $(‘div‘).filter(function(i,elem){
        return elem.className == ‘box‘;
        
    }).css(‘border‘,‘1px red solid‘);
    */
    if ( jQuery.isFunction( qualifier ) ) {
        //grep是elements每一个元素执行function(),函数传入的实参一个是每一个元素另一个元素下标,这里elem, i是形参, 并判断函数的返回值,函数体这里定义,
        return jQuery.grep( elements, function( elem, i ) {
            //!!是把undefined和null转换成false
            return !!qualifier.call( elem, i, elem ) !== not;
        });//返回的是满足函数条件的elements:div元素集合

    }

    /*
    var oBox = document.getElementsByClassName(‘box‘)[0];
    $(‘div‘).filter(oBox).css(‘border‘,‘1px red solid‘);
    */
    if ( qualifier.nodeType ) {
        return jQuery.grep( elements, function( elem ) {
            return ( elem === qualifier ) !== not;
        });

    }

    if ( typeof qualifier === "string" ) {
        //isSimple = /^.[^:#\[\.,]*$/  任意字符开头,不包括:#[.,一直到结束
        if ( isSimple.test( qualifier ) ) {//匹配成功:.box,#div1,:odd ,ul,li,div
            return jQuery.filter( qualifier, elements, not );
        }
        //匹配不成功div:odd,ul #li,ul[title=‘hello‘],div.box,ul,li
        qualifier = jQuery.filter( qualifier, elements );
    }
        //匹配不成功
    return jQuery.grep( elements, function( elem ) {
        return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not;
    });
}


var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
    rtagName = /<([\w:]+)/,
    rhtml = /<|&#?\w+;/,
    rnoInnerhtml = /<(?:script|style|link)/i,
    manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
    // checked="checked" or checked
    rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
    rscriptType = /^$|\/(?:java|ecma)script/i,
    rscriptTypeMasked = /^true\/(.*)/,
    rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,

    // We have to close these tags to support XHTML (#13200)
    wrapMap = {

        // Support: IE 9
        option: [ 1, "<select multiple=‘multiple‘>", "</select>" ],

        thead: [ 1, "<table>", "</table>" ],
        col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
        tr: [ 2, "<table><tbody>", "</tbody></table>" ],
        td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],

        _default: [ 0, "", "" ]
    };

// Support: IE 9
wrapMap.optgroup = wrapMap.option;

wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

jQuery.fn.extend({
//$(‘div‘).text(‘<h1>标题</h1>‘);//不会被解析成标签
    text: function( value ) {
        return jQuery.access( this, function( value ) {
            return value === undefined ?
                jQuery.text( this ) ://获取
                this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) );
        }, null, value, arguments.length );
    },

    /*
    $(‘span‘).append( oDiv );
    $(‘span‘).append( $(‘div‘) );
    $(‘span‘).append( ‘<div></div>‘ );
    */
    append: function() {
        return this.domManip( arguments, function( elem ) {
            if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
                var target = manipulationTarget( this, elem );
                target.appendChild( elem );
            }
        });
    },

    /*
    $(‘div‘).prepend( $(‘span‘) );//sopan添加到div里面的最前面
    //<div><span></span>div</div>
    */
    prepend: function() {
        return this.domManip( arguments, function( elem ) {
            if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
                //manipulationTarget是做兼容,返回的是this
                var target = manipulationTarget( this, elem );
                target.insertBefore( elem, target.firstChild );//firstChild第一个子节点
            }
        });
    },

    before: function() {
        return this.domManip( arguments, function( elem ) {
            if ( this.parentNode ) {
                //添加到this前面
                this.parentNode.insertBefore( elem, this );
            }
        });
    },

    after: function() {
        return this.domManip( arguments, function( elem ) {
            if ( this.parentNode ) {
                //添加到下一个兄弟节点前面。就是后面
                this.parentNode.insertBefore( elem, this.nextSibling );
            }
        });
    },

    // $(‘div‘).remove(‘.box‘);//删除节点
    remove: function( selector, keepData ) {
        var elem,
            elems = selector ? jQuery.filter( selector, this ) : this,
            i = 0;

        for ( ; (elem = elems[i]) != null; i++ ) {
            if ( !keepData && elem.nodeType === 1 ) {
                //gatAll删除子标签
                jQuery.cleanData( getAll( elem ) );//删除节点并且删除点击事件
            }

            if ( elem.parentNode ) {
                //标签中有script标签
                if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
                    setGlobalEval( getAll( elem, "script" ) );
                }
                elem.parentNode.removeChild( elem );//删除这个节点,原生方法
            }
        }

        return this;
    },

    empty: function() {
        var elem,
            i = 0;

        for ( ; (elem = this[i]) != null; i++ ) {
            if ( elem.nodeType === 1 ) {

                // 清空data数据缓存和点击事件
                jQuery.cleanData( getAll( elem, false ) );

                // Remove any remaining nodes
                elem.textContent = "";
            }
        }

        return this;
    },

    //var cloneDiv3 = $(‘div‘).clone(true,true);//子元素有点击事件
    clone: function( dataAndEvents, deepDataAndEvents ) {
        dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
        deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
/*
(this.) map: function( callback ) {
    return this.pushStack( jQuery.map(
                                    this, 
                                    function( elem, i ) {
                                        return callback.call( elem, i, elem );
                                    }
                                )
                           );
     },
*/
        return this.map( function () {//this的每一个元素,调用f,返回f结果集合,结果.preObject= $(‘div‘), 调用内部clone方法
            return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
        });
    },

    html: function( value ) {
        return jQuery.access( this, function( value ) {
            var elem = this[ 0 ] || {},
                i = 0,
                l = this.length;

            if ( value === undefined && elem.nodeType === 1 ) {
                return elem.innerHTML;//$(‘span‘).html();原生获取方式
            }

            //设置$(‘span‘).html(‘<tr></tr>‘);
            // See if we can take a shortcut and just use innerHTML
            if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
                !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

                value = value.replace( rxhtmlTag, "<$1></$2>" );

                try {
                    for ( ; i < l; i++ ) {
                        elem = this[ i ] || {};

                        // Remove element nodes and prevent memory leaks
                        if ( elem.nodeType === 1 ) {
                            jQuery.cleanData( getAll( elem, false ) );
                            elem.innerHTML = value;
                        }
                    }

                    elem = 0;

                // If using innerHTML throws an exception, use the fallback method
                } catch( e ) {}
            }

            if ( elem ) {
                this.empty().append( value );//append添加节点
            }
        }, null, value, arguments.length );
    },

    replaceWith: function() {
        var
            // Snapshot the DOM in case .domManip sweeps something relevant into its fragment
            args = jQuery.map( this, function( elem ) {
                return [ elem.nextSibling, elem.parentNode ];
            }),
            i = 0;

        // Make the changes, replacing each context element with the new content
        this.domManip( arguments, function( elem ) {
            var next = args[ i++ ],
                parent = args[ i++ ];

            if ( parent ) {
                // Don‘t use the snapshot next if it has moved (#13810)
                if ( next && next.parentNode !== parent ) {
                    next = this.nextSibling;
                }
                jQuery( this ).remove();
                parent.insertBefore( elem, next );
            }
        // Allow new content to include elements from the context set
        }, true );

        // Force removal if there was no new content (e.g., from empty arguments)
        return i ? this : this.remove();
    },
    
    //$(‘div‘).detach();
    detach: function( selector ) {
        return this.remove( selector, true );
    },

    domManip: function( args, callback, allowIntersection ) {

        // Flatten any nested arrays
        args = core_concat.apply( [], args );

        var fragment, first, scripts, hasScripts, node, doc,
            i = 0,
            l = this.length,
            set = this,
            iNoClone = l - 1,
            value = args[ 0 ],
            isFunction = jQuery.isFunction( value );
/*
    $(‘span‘).append(function(){
        return ‘hello‘;
    });
*/
        // We can‘t cloneNode fragments that contain checked, in WebKit
        if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
            return this.each(function( index ) {
                var self = set.eq( index );
                if ( isFunction ) {
                    args[ 0 ] = value.call( this, index, self.html() );
                }
//重新调用$(‘span‘).append(‘hello‘)
                self.domManip( args, callback, allowIntersection );
            });
        }

        if ( l ) {
//$(‘span‘).append(‘<h1>hello</h1>‘); 文档碎片
            fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
            first = fragment.firstChild;

            if ( fragment.childNodes.length === 1 ) {
                fragment = first;
            }

            if ( first ) {
                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: QtWebKit
                            // jQuery.merge because core_push.apply(_, arraylike) throws
                            jQuery.merge( scripts, getAll( node, "script" ) );
                        }
                    }

                    callback.call( this[ 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 || "" ) &&
                            !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {

                            if ( node.src ) {
                                // Hope ajax is available...
                                jQuery._evalUrl( node.src );
                            } else {
                                jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
                            }
                        }
                    }
                }
            }
        }

        return this;
    }
});

jQuery.each({
    appendTo: "append",
    prependTo: "prepend",
    insertBefore: "before",
    insertAfter: "after",
    replaceAll: "replaceWith"
}, function( name, original ) {
    //$(‘span‘).appendTo( $(‘div‘) ).css(‘border‘,‘1px red solid‘);
    jQuery.fn[ name ] = function( selector ) {
        var elems,
            ret = [],
            insert = jQuery( selector ),//$(‘div‘)
            last = insert.length - 1,
            i = 0;

        for ( ; i <= last; i++ ) {
            elems = i === last ? this : this.clone( true );
            //调用jQuery($(‘div‘)[i]).append($(‘span‘))
            jQuery( insert[ i ] )[ original ]( elems );

            // Support: QtWebKit
            // .get() because core_push.apply(_, arraylike) throws
            core_push.apply( ret, elems.get() );
        }

        return this.pushStack( ret );
    };
});

jQuery.extend({
    //jQuery.clone( $(‘div‘)每一个, true, true );
    clone: function( elem, dataAndEvents, deepDataAndEvents ) {
        var i, l, srcElements, destElements,
            clone = elem.cloneNode( true ),//原生的方式,克隆,仅仅复制html节点包括子节点,事件缓存没有复制过来
            //当前页
            inPage = jQuery.contains( elem.ownerDocument, elem );
/*        
console.log(clone);//节点包括子节点。false就只有外层节点,没有子节点
var dd = getAll( elem );//[div, span, p]
var rr = getAll( clone );//[div, span, p]    
*/
/*  Support: IE >= 9   if是兼容性

    $(‘input‘).prop(‘checked‘,true);
    $(‘input‘).clone().appendTo( ‘body‘ );//jQuery克隆过去也是选中的,但是原生的是没有选中的,
*/
        if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) {

            // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
            destElements = getAll( clone );//数组
            srcElements = getAll( elem );

            for ( i = 0, l = srcElements.length; i < l; i++ ) {
                fixInput( srcElements[ i ], destElements[ i ] );
            }
        }

        // Copy the events from the original to the clone
        if ( dataAndEvents ) {//克隆自身的事件
            if ( deepDataAndEvents ) {//克隆子项的事件
                srcElements = srcElements || getAll( elem );
                destElements = destElements || getAll( clone );

                for ( i = 0, l = srcElements.length; i < l; i++ ) {
                    cloneCopyEvent( srcElements[ i ], destElements[ i ] );
                }
            } else {//不克隆子项只克隆自身,原节点、复制的节点
                cloneCopyEvent( elem, clone );
            }
        }

        // 克隆的元素包含script标签
        destElements = getAll( clone, "script" );
        if ( destElements.length > 0 ) {
            //把script标签设置为全局script执行
            setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
        }

        // Return the cloned set
        return clone;
    },

    //创建文档碎片
    buildFragment: function( elems, context, scripts, selection ) {
        var elem, tmp, tag, wrap, contains, j,
            i = 0,
            l = elems.length,
            fragment = context.createDocumentFragment(),
            nodes = [];//实现的结果

        for ( ; i < l; i++ ) {
            elem = elems[ i ];//每一个元素做处理

            if ( elem || elem === 0 ) {

                // Add nodes directly
                if ( jQuery.type( elem ) === "object" ) {
                    // Support: QtWebKit
                    // jQuery.merge because core_push.apply(_, arraylike) throws
                    jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );

                // Convert non-html into a text node
                } else if ( !rhtml.test( elem ) ) {
                    nodes.push( context.createTextNode( elem ) );

//$(‘span‘).append( ‘<h1>hello</h1><h1>hello</h1><h1>hello</h1>‘ ); 添加多标签用到文档碎片,效率高,
                } else {
                    tmp = tmp || fragment.appendChild( context.createElement("div") );

                    // Deserialize a standard representation
                    tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase();
                    wrap = wrapMap[ tag ] || wrapMap._default;
                    tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
/*
    wrapMap = {

        // Support: IE 9
        option: [ 1, "<select multiple=‘multiple‘>", "</select>" ],

        thead: [ 1, "<table>", "</table>" ],
        col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
        tr: [ 2, "<table><tbody>", "</tbody></table>" ],
        td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],

        _default: [ 0, "", "" ]
    };
*/
                    j = wrap[ 0 ];
                    while ( j-- ) {
                        tmp = tmp.lastChild;
                    }

                    // Support: QtWebKit
                    // jQuery.merge because core_push.apply(_, arraylike) throws
                    jQuery.merge( nodes, tmp.childNodes );

                    // Remember the top-level container
                    tmp = fragment.firstChild;

                    // Fixes #12346
                    // Support: Webkit, IE
                    tmp.textContent = "";
                }
            }
        }

        // Remove wrapper from fragment
        fragment.textContent = "";

        i = 0;
        while ( (elem = nodes[ i++ ]) ) {

            // #4087 - If origin and destination elements are the same, and this is
            // that element, do not do anything
            if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
                continue;
            }

            contains = jQuery.contains( elem.ownerDocument, elem );

            // Append to fragment
            tmp = getAll( fragment.appendChild( elem ), "script" );

            // Preserve script evaluation history
            if ( contains ) {
                setGlobalEval( tmp );
            }

            // Capture executables
            if ( scripts ) {  
                j = 0;
                while ( (elem = tmp[ j++ ]) ) {
                    if ( rscriptType.test( elem.type || "" ) ) {
                        scripts.push( elem );
                    }
                }
            }
        }

        return fragment;
    },

    //清除元素的点击事件和数据(data保存的)
    cleanData: function( elems ) {
        var data, elem, events, type, key, j,
            special = jQuery.event.special,
            i = 0;

        for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
            if ( Data.accepts( elem ) ) {
                key = elem[ data_priv.expando ];
//删除元素的点击事件,data里的事件
                if ( key && (data = data_priv.cache[ key ]) ) {
                    events = Object.keys( data.events || {} );
                    if ( events.length ) {
                        for ( j = 0; (type = events[j]) !== undefined; j++ ) {
                            if ( special[ type ] ) {//特殊事件,自定义事件
                                jQuery.event.remove( elem, type );

                            // This is a shortcut to avoid jQuery.event.remove‘s overhead
                            } else {
                                jQuery.removeEvent( elem, type, data.handle );
                            }
                        }
                    }
                    if ( data_priv.cache[ key ] ) {//删除缓存data里的
                        // Discard any remaining `private` data
                        delete data_priv.cache[ key ];
                    }
                }
            }
            // Discard any remaining `user` data
            delete data_user.cache[ elem[ data_user.expando ] ];
        }
    },

    _evalUrl: function( url ) {
        return jQuery.ajax({
            url: url,
            type: "GET",
            dataType: "script",
            async: false,
            global: false,
            "throws": true
        });
    }
});

// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
    return jQuery.nodeName( elem, "table" ) &&
        jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
//没有tbody自动添加tbody
        elem.getElementsByTagName("tbody")[0] ||
            elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
        elem;
}

// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
    elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
    return elem;
}
function restoreScript( elem ) {
    var match = rscriptTypeMasked.exec( elem.type );

    if ( match ) {
        elem.type = match[ 1 ];
    } else {
        elem.removeAttribute("type");
    }

    return elem;
}

// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
    var l = elems.length,
        i = 0;

    for ( ; i < l; i++ ) {
        data_priv.set(
            elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
        );
    }
}

//cloneCopyEvent( elem, clone );  克隆事件,原节点目的节点,节点已经由原生方法克隆了,
function cloneCopyEvent( src, dest ) {
    var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;

    if ( dest.nodeType !== 1 ) {
        return;
    }

    // 1. 从data中克隆事件
    if ( data_priv.hasData( src ) ) {
        pdataOld = data_priv.access( src );
        pdataCur = data_priv.set( dest, pdataOld );
        events = pdataOld.events;

        if ( events ) {
            delete pdataCur.handle;
            pdataCur.events = {};
//遍历
            for ( type in events ) {
                for ( i = 0, l = events[ type ].length; i < l; i++ ) {
                    jQuery.event.add( dest, type, events[ type ][ i ] );
                }
            }
        }
    }

    // 2. 从data中克隆数据
    if ( data_user.hasData( src ) ) {
        udataOld = data_user.access( src );
        udataCur = jQuery.extend( {}, udataOld );
//遍历
        data_user.set( dest, udataCur );
    }
}


function getAll( context, tag ) {
    var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
            context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
            [];

    return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
        jQuery.merge( [ context ], ret ) :
        ret;
}

// Support: IE >= 9
function fixInput( src, dest ) {
    var nodeName = dest.nodeName.toLowerCase();

    // Fails to persist the checked state of a cloned checkbox or radio button.
    if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
        dest.checked = src.checked;

    // Fails to return the selected option to the default selected state when cloning options
    } else if ( nodeName === "input" || nodeName === "textarea" ) {
        dest.defaultValue = src.defaultValue;
    }
}
jQuery.fn.extend({
    /*
    $(‘span‘).wrap(‘<div>‘);//每个span包一个div    $(‘span‘).wrapAll(‘<div>‘);//所有span只包一个div,如果span里面有其他标签会把这个标签移出来
    $(‘span‘).wrapInner(‘<div>‘);//每个span里面包一个div
    $(‘span‘).unwrap();//删除父级
    */
    wrapAll: function( html ) {
        var wrap;

        if ( jQuery.isFunction( html ) ) {
            /*
                $(‘span‘).wrapAll(function(){
                    return ‘<div>‘;
                });
            */
            return this.each(function( i ) {//函数执行一次,然后用函数返回值再调用
                jQuery( this ).wrapAll( html.call(this, i) );
            });
        }

        if ( this[ 0 ] ) {

            // $(‘span‘).wrapAll(‘<div>‘); 创建div对象并且克隆节点,事件也克隆
            wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );

            if ( this[ 0 ].parentNode ) {
                wrap.insertBefore( this[ 0 ] );//添加到第一个span的前面
            }

            wrap.map(function() {
                var elem = this;

                while ( elem.firstElementChild ) {
                    elem = elem.firstElementChild;
                }

                return elem;
            }).append( this );
        }

        return this;
    },

    wrapInner: function( html ) {
        if ( jQuery.isFunction( html ) ) {
            return this.each(function( i ) {
                jQuery( this ).wrapInner( html.call(this, i) );
            });
        }

        return this.each(function() {
            var self = jQuery( this ),
                contents = self.contents();

            if ( contents.length ) {
                contents.wrapAll( html );

            } else {
                self.append( html );
            }
        });
    },
//分别包装
    wrap: function( html ) {
        var isFunction = jQuery.isFunction( html );

        return this.each(function( i ) {
            jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
        });
    },
//找到父级,替换操作,删除父级,不能是body
    unwrap: function() {
        return this.parent().each(function() {
            if ( !jQuery.nodeName( this, "body" ) ) {
                jQuery( this ).replaceWith( this.childNodes );
            }
        }).end();
    }
});

 

以上是关于jQuery08源码 (5140 , 6057) DOM操作 : 添加 删除 获取 包装 DOM筛选的主要内容,如果未能解决你的问题,请参考以下文章

HDU 6057 Kanade's convolution

HDU-6057 Kanade's convolution

LOJ 6057 - [HNOI2016]序列 加强版再加强版

hdu 6057 Kanade's convolution(子集卷积)

Leetcode6057: 求满足条件的子树节点的平均值的节点个数(周赛)

Leetcode6057: 求满足条件的子树节点的平均值的节点个数(周赛)