admin管理员组

文章数量:1417554

I looked at the jQuery source code for the .empty() function:

empty: function() {
        for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
            // Remove element nodes and prevent memory leaks
            if ( elem.nodeType === 1 ) {
                jQuery.cleanData( elem.getElementsByTagName("*") );
            }

            // Remove any remaining nodes
            while ( elem.firstChild ) {
                elem.removeChild( elem.firstChild );
            }
        }​

Couldn't it be a lot simpler with just changing the innerHTML to an empty string:

empty: function() {
        for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
                elem.innerHTML = "";
        }​

The empty docs:

Description: Remove all child nodes of the set of matched elements from the DOM.

I looked at the jQuery source code for the .empty() function:

empty: function() {
        for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
            // Remove element nodes and prevent memory leaks
            if ( elem.nodeType === 1 ) {
                jQuery.cleanData( elem.getElementsByTagName("*") );
            }

            // Remove any remaining nodes
            while ( elem.firstChild ) {
                elem.removeChild( elem.firstChild );
            }
        }​

Couldn't it be a lot simpler with just changing the innerHTML to an empty string:

empty: function() {
        for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
                elem.innerHTML = "";
        }​

The empty docs:

Description: Remove all child nodes of the set of matched elements from the DOM.

Share Improve this question edited May 5, 2012 at 23:58 Mike Samuel 121k30 gold badges227 silver badges254 bronze badges asked Apr 24, 2012 at 20:24 gdorongdoron 150k59 gold badges302 silver badges371 bronze badges 2
  • It's explained by this ment in the code: // Remove element nodes and prevent memory leaks... – nnnnnn Commented Apr 24, 2012 at 21:28
  • @nnnnnn. Yes, I'm actually asking how can it cause a memory leaks... – gdoron Commented Jun 6, 2012 at 22:26
Add a ment  | 

1 Answer 1

Reset to default 11

Just think about .data() expandos and event handlers... By just removing the DOM, you would create memory leaks every time.

本文标签: javascriptWhy is the jquery empty function so complicatedStack Overflow