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();
    }
});
时间: 2024-10-17 02:54:27

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

jquery16 DOM操作 : 添加 删除 获取 包装 DOM筛选

<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <script src="jquery-2.0.3.js"></script> <script> 一些变

jquery17 DOM操作 : 添加 删除 获取 包装 DOM筛选

<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <script src="jquery-2.0.3.js"></script> <script> $(f

OpenStack_Swift源码分析——创建Ring及添加设备源码详细分析

1 创建Ring 代码详细分析 在OpenStack_Swift--Ring组织架构中我们详细分析了Ring的具体工作过程,下面就Ring中增加设备,删除设备,已经重新平衡的实现过程作详细的介绍. 首先看RingBuilder类 def __init__(self, part_power, replicas, min_part_hours): #why 最大 2**32 if part_power > 32: raise ValueError("part_power must be at

调试JDK源码时可编辑操作的实现

目录 一.解压源码压缩包 二.创建Java项目 三.复制源码文件到文件夹 四.Platform Settings中新增一个SDK 五.修改新建SDK的 Sourcepath 配置 六.修改 Project 以及 Modules 的 SDK 七.项目结构图 八.测试调试过程中对源码进入注释 以下操作在以下环境中测试通过:idea 2019.3,jdk8源码包 一.解压源码压缩包 从jdk安装目录中找到 src.zip 的源码压缩包,解压后得到源码文件夹 二.创建Java项目 因主要目的是调试源码,

jQuery 源码分析(十三) 数据操作模块 DOM属性 详解

jQuery的属性操作模块总共有4个部分,本篇说一下第2个部分:DOM属性部分,用于修改DOM元素的属性的(属性和特性是不一样的,一般将property翻译为属性,attribute翻译为特性) DOM属性的静态方法接口如下: prop(elem, name, value)    ;设置或读取DOM属性,有两种用法,如下 ·$.prop(elem,name,value)      ;传入第三个参数表示设置elem元素的name属性值为value ·$.prop(elem,name,)      

Linux安装yum源码包及相关操作

一.使用场景 很多时候下载的rpm包所提供的功能并不符合我们的需要,或者只需要使用其中一部分功能的时候,就需要进行源码安装.源码安装前,首先使用 yum grouplist 确认 Development tools 和 Server Platform Development这两个组已经被安装. 二.相关知识详解 1.make工具 所有的程序都需要gcc编译后才能执行,项目的开发者为了简化使用者的编译步骤,当时用make工具后,make会调用gcc对程序进行编译,所以说make是一种项目编译工具,

多目标遗传算法 ------ NSGA-II (部分源码解析) 交叉操作 crossover.c

遗传算法中的交叉操作是 对NSGA-II  源码分析的  最后一部分, 这一部分也是我 从读该算法源代码和看该算法论文理解偏差最大的  函数模块. 这里,首先提一下,遗传算法的  交叉操作.变异操作都是需要设定概率的, 即交叉概率和变异概率. 假设种群个体 大小为  popsize ,  那么交叉操作需要进行 popsize/2 次 ,   变异操作需要进行 popsize 次, 其中每次操作的时候都需要随机生成一个随机数来与给定的概率进行判断,若小于给定的概率则继续执行否则退出该操作. 如果继

Robotium源码解读-native/webview控件的获取和操作

之前基本上没接触过移动端的UITest测试,之前因为一些需求临时赶鸭子上架采用了UIAutomator,但是后来发现webview没办法识别,在预研过程中,发现Robotium跟Appium这两个神器.由于Robotium提供了webview的解析方式,遂决定研究一下. 一.环境准备以及初始化 用来说明的用例采用的是Robotium官网的一个tutorial用例-Notepad @RunWith(AndroidJUnit4.class) public class NotePadTest { pr

linux 源码安装apache2.4并添加服务

源码安装apache,路径 /usr/local/httpd24 1.安装apr yum -y install epel-release  wget -c http://archive.apache.org/dist/apr/apr-1.5.2.tar.gz tar xf apr-1.5.2.tar.gz cd apr-1.5.2  ./configure --prefix=/usr/local/apr;echo $? make && make install;echo $?  cd ..