码迷,mamicode.com
首页 > 其他好文 > 详细

节点操作

时间:2014-06-18 21:49:47      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   java   

js中DOM操作占了极大的部分,对于节点的操作主要有节点插入,节点移除,节点复制,还有一些innerHTML,innerText,outerHTML相关的东西。

节点的插入

原生的DOM接口非常简单,参数确定,方法调用方便。jQuery对这些原生接口进行利用,组装出了一些列更为犀利的方法,append、prepend、before、after、replace等。而且因为这几个方法是用频率实在频繁,于是W3C在DOM4中决定原生支持它们。在jQuery中的原生代码如下:

bubuko.com,布布扣
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 );
        }
    });
},

prepend: function() {
    return this.domManip( arguments, function( elem ) {
        if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
            var target = manipulationTarget( this, elem );
            target.insertBefore( elem, target.firstChild );
        }
    });
},

before: function() {
    return this.domManip( arguments, function( elem ) {
        if ( this.parentNode ) {
            this.parentNode.insertBefore( elem, this );
        }
    });
},

after: function() {
    return this.domManip( arguments, function( elem ) {
        if ( this.parentNode ) {
            this.parentNode.insertBefore( elem, this.nextSibling );
        }
    });
},
replaceWith: function() {
    var arg = arguments[ 0 ];

    // Make the changes, replacing each context element with the new content
    this.domManip( arguments, function( elem ) {
        arg = this.parentNode;

        jQuery.cleanData( getAll( this ) );

        if ( arg ) {
            arg.replaceChild( elem, this );
        }
    });

    // Force removal if there was no new content (e.g., from empty arguments)
    return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
domManip: function( args, callback ) {

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

    var first, node, hasScripts,
        scripts, doc, fragment,
        i = 0,
        l = this.length,
        set = this,
        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 this.each(function( index ) {
            var self = set.eq( index );
            if ( isFunction ) {
                args[0] = value.call( this, index, self.html() );
            }
            self.domManip( args, callback );
        });
    }

    if ( l ) {
        fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, 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 ) {
                        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 || "" ) &&
                        !jQuery._data( 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 {
                            jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
                        }
                    }
                }
            }

            // Fix #11809: Avoid leaking memory
            fragment = first = null;
        }
    }

    return this;
}
View Code
bubuko.com,布布扣
jQuery.each({
    appendTo: "append",
    prependTo: "prepend",
    insertBefore: "before",
    insertAfter: "after",
    replaceAll: "replaceWith"
}, function( name, original ) {
    jQuery.fn[ name ] = function( selector ) {
        var elems,
            i = 0,
            ret = [],
            insert = jQuery( selector ),
            last = insert.length - 1;

        for ( ; i <= last; i++ ) {
            elems = i === last ? this : this.clone(true);
            jQuery( insert[i] )[ original ]( elems );

            // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
            push.apply( ret, elems.get() );
        }

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

基本的思想基本上都是相似的,接口只是一个空心的壳而已,只是提供了一个便于记忆的名字,具体的实现还是转到内部更为复杂的函数中去了。

还有,在自己写框架的时候,对于节点的操作,特别是节点添加的形式,要注意一个要点,NodeList是实时更新的,对于插入操作,会引起NodeList立刻更新,这时就要注意不要进入死循环了。

window.onload = function(){
    var divs = document.body.getElementsByTagName(‘div‘);
    for(var i = 0; i < divs.length, i++){
        var ele = document.createElement(‘div‘);
        ele.appendChild(document.createTextNode(‘New Link!‘));
        divs.appendChild(ele);
    }
}

还有一个点是关于节点复制方面的,这个在下面就会讲到。

节点的复制

在IE下对节点的复制,有一些奇怪的问题,其中著名的就是 IE 会自动复制在节点上添加的事件,同时IE6~IE8会复制通过node.aa = ‘xx‘ 形式添加的属性,而标准浏览器只会复制标签内的属性和通过setAttribute设置的属性

<a id=‘aa‘ title = ‘title‘ href = ‘#‘>try</a>

window.onload = function(){
    var node = document.getElementById(‘aa‘);
    node.expando.key = 1;
    node.setAttribute(‘attr‘,‘attr‘);
    var clone = node.cloneNode(false);
    alert(clone.id); //aa
    alert(clone.getAttribute(‘title‘)); //‘title‘
    alert(clone.getAttribute(‘attr‘)); //‘attr‘
    node.expando.key = 2;
    alert(clone.expando.key);  //IE 2 其它 undefined
}

如果仅仅是这样,开发者还是比较容易解决以上问题的,但是IE中还会出现少复制现象,对于此,只能一步步进行处理了(from mass):

    function fixNode(clone, src) {
        if(src.nodeType == 1) {
            //只处理元素节点
            var nodeName = clone.nodeName.toLowerCase();
            //clearAttributes方法可以清除元素的所有属性值,如style样式,或者class属性,与attachEvent绑定上去的事件
            clone.clearAttributes();
            //复制原对象的属性到克隆体中,但不包含原来的事件, ID,  NAME, uniqueNumber
            clone.mergeAttributes(src, false);
            //IE6-8无法复制其内部的元素
            if(nodeName === "object") {
                clone.outerHTML = src.outerHTML;
            } else if(nodeName === "input" && (src.type === "checkbox" || src.type == "radio")) {
                //IE6-8无法复制chechbox的值,在IE6-7中也defaultChecked属性也遗漏了
                if(src.checked) {
                    clone.defaultChecked = clone.checked = src.checked;
                }
                // 除Chrome外,所有浏览器都会给没有value的checkbox一个默认的value值”on”。
                if(clone.value !== src.value) {
                    clone.value = src.value;
                }
            } else if(nodeName === "option") {
                clone.selected = src.defaultSelected; // IE6-8 无法保持选中状态
            } else if(nodeName === "input" || nodeName === "textarea") {
                clone.defaultValue = src.defaultValue; // IE6-8 无法保持默认值
            } else if(nodeName === "script" && clone.text !== src.text) {
                clone.text = src.text; //IE6-8不能复制script的text属性
            }

        }
    }

jQuery:

    clone: function( dataAndEvents, deepDataAndEvents ) {
        dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
        deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

        return this.map(function() {
            return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
        });
    }

这段这是一个处理参数的空壳,具体还是再jQuery.clone中:

bubuko.com,布布扣
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
    var destElements, node, clone, i, srcElements,
        inPage = jQuery.contains( elem.ownerDocument, elem );

    if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
        clone = elem.cloneNode( true );

    // IE<=8 does not properly clone detached, unknown element nodes
    } else {
        fragmentDiv.innerHTML = elem.outerHTML;
        fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
    }

    if ( (!support.noCloneEvent || !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 );

        // Fix all IE cloning issues
        for ( i = 0; (node = srcElements[i]) != null; ++i ) {
            // Ensure that the destination node is not null; Fixes #9587
            if ( destElements[i] ) {
                fixCloneNodeIssues( node, 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; (node = srcElements[i]) != null; i++ ) {
                cloneCopyEvent( node, destElements[i] );
            }
        } else {
            cloneCopyEvent( elem, clone );
        }
    }

    // Preserve script evaluation history
    destElements = getAll( clone, "script" );
    if ( destElements.length > 0 ) {
        setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
    }

    destElements = srcElements = node = null;

    // Return the cloned set
    return clone;
}
View Code

可以看到,jQuery.clone中在不能保证cloneNode正常的情况下,用了outerHTML来操作,然后拷贝事件,属性。整体代码很臃肿,但是这也是必须的。现在能做的就是等到用户放弃IE6了。

节点的移除

节点的移除在IE6~7中就要涉及内存泄露这类的问题了。在浏览器中,移除节点主要有removeNode,removeChild,deleteContents。removeNode是IE中的方法,移除目标节点,保留子节点,参数为true时同removeChild。removeChild在IE6~7中有内存泄露问题。deleteContents则是偏门API。

首先是为啥IE6~7中会内存泄露。IE6~7中有个叫做超空间的概念。从文档中移除的节点(有Javascript关联)并不会消失掉,而是跑到了一个叫做超空间的地方。可以用parentNode来判断是否存在超空间。

window.onload = function(){
    var div = document.createElement(‘div‘);
    alert(div.parentNode); //null
    document.body.appendChild(div);
    document.body.removeChild(div);
    alert(div.parentNode); //IE6~8 object 其它 null
}

我们来看下EXT是怎么做的:

removeNode : isIE ? function(){  
       var d;  
       return function(n){  
            if(n && n.tagName != ‘BODY‘){  
                 d = d || DOC.createElement(‘div‘);  
                 d.appendChild(n);  
                 d.innerHTML = ‘‘;  
            }  
       }  
    }() : function(n){  
        if(n && n.parentNode && n.tagName != ‘BODY‘){  
             n.parentNode.removeChild(n);  
        }  
    }  

在这里,我们可以发现,它使用了innerHTML来进行移除。innerHTML在IE低版本中进行移除,会导致直接清空内部内容,只剩空壳。相比于IE对内存管理的失败,这个正是我们寻找的方法!

 

先写到这,晚上要毕业季谢师宴,估计要被灌酒灌倒死了,于是大清早爬起来把这篇博客写完了,希望晚上我还能活着回来。。。。。。

 

节点操作,布布扣,bubuko.com

节点操作

标签:des   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/cyITtech/p/3790066.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!