2013-07-09 6 views
20

.empty対jQueryの差異.htmlを( "")()

$('#divid').html(""); 

$('#divid').empty(); 

の違いは、両方の内部 jQueryの内部に同じ動作をしているのさ。 js?

とどちらを使用する方が良いですか。他の多くのものの中でhtml機能のソースコードから、

+1

http://jsperf.com/ –

+5

重複するマークには現存する質問へのリンクが含まれている必要があります – Evan

+1

'' .empty() ''は**はるかに高速です**:http://jsperf.com/jquery- empty-vs-html/17 – AmpT

答えて

23

Tは.empty()が高速であると考える方が良いです。これは.empty()

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); 
    } 
} 

return this; } 

のためのjQueryの源であり、これはjQueryの.html("")ソースです:

html: function(value) { 
if (value === undefined) { 
    return this[0] && this[0].nodeType === 1 ? 
     this[0].innerHTML.replace(rinlinejQuery, "") : 
     null; 

// See if we can take a shortcut and just use innerHTML 
} else if (typeof value === "string" && !rnocache.test(value) && 
    (jQuery.support.leadingWhitespace || !rleadingWhitespace.test(value)) && 
    !wrapMap[ (rtagName.exec(value) || ["", ""])[1].toLowerCase() ]) { 

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

    try { 
     for (var i = 0, l = this.length; i < l; i++) { 
      // Remove element nodes and prevent memory leaks 
      if (this[i].nodeType === 1) { 
       jQuery.cleanData(this[i].getElementsByTagName("*")); 
       this[i].innerHTML = value; 
      } 
     } 

    // If using innerHTML throws an exception, use the fallback method 
    } catch(e) { 
     this.empty().append(value); 
    } 

} else if (jQuery.isFunction(value)) { 
    this.each(function(i){ 
     var self = jQuery(this); 

     self.html(value.call(this, i, self.html())); 
    }); 

} else { 
    this.empty().append(value); 
} 

return this; } 

それは明らかだ、あなたはあなたの最高を選択することができます。

+1

'' .empty() ''は上司です! **もっと速い**:http://jsperf.com/jquery-empty-vs-html/17 – AmpT

+0

7年以上のJS開発の後、私はついにこの#facepalmを学ぶ –

2

 if (elem) { 
      this.empty().append(value); 
     } 

のでhtml通話empty。したがって、わずかにemptyと呼ぶほうが簡単です。もちろん、それはもっと読みやすいです。

5

私はJSperfで次のように試して、$( '#divid')を使って見つけました。

enter image description here