javascript - Why is the jquery empty function so complicated? - Stack Overflow

I looked at the jQuery source code for the .empty() function:empty: function() {for ( var i = 0, elem;

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745271096a4619750.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信