29

要素を選択するときに、より良いパフォーマンス$('#childDiv2 .txtClass')を期待していました。しかし、このパフォーマンス分析によると、この中で最高のセレクターです。私はJQuery 1.7.2を使用しています。これについて誰か説明がありますか?$('#childDiv2 input.txtClass')<input type="text" id="txtID" class="txtClass"/> $('.txtClass');

クラスセレクターのパフォーマンス分析

HTML

<div class="childDiv2">
    <input type="text" id="txtID" class="txtClass"/>
    <p class="child">Blah Blah Blah</p>
</div>​

JS

$('.txtClass');
$('#childDiv2 .txtClass')
$('#childDiv2 > .txtClass')
$('input.txtClass')
$('#childDiv2 input.txtClass')
4

4 に答える 4

55

最新のブラウザーは、特定のクラスを持つ要素を返す非常に効率的なgetElementsByClassName()メソッドを公開しています。そのため、単一のクラスセレクターの方が高速です。

あなたの例を詳しく説明するには:

$(".txtClass")                  =>  getElementsByClassName()

$("#childDiv2 .txtClass")       =>  getElementById(),
                                    then getElementsByClassName()

$("#childDiv2 > .txtClass")     =>  getElementById(),
                                    then iterate over children and check class

$("input.txtClass")             =>  getElementsByTagName(),
                                    then iterate over results and check class

$("#childDiv2 input.txtClass")  =>  getElementById(),
                                    then getElementsByTagName(),
                                    then iterate over results and check class

ご覧のとおり、最新のブラウザーで最初のフォームが最速であることは非常に論理的です。

于 2012-07-28T07:23:41.513 に答える
8
var obj = document.getElementById("childDiv");
xxx = obj.getElementsByClassName("txtClass");

は 30 倍高速です。

http://jsperf.com/selectors-perf/6

于 2013-03-12T18:14:51.347 に答える
6

CSS セレクターは右から左に解析されます。だからあなたの例

$('#childDiv2 .txtClass')

完了するには 2 つのアクションが必要です。最初に class を持つすべての要素を見つけますtxtClass。次に、各要素が id の要素の子であることを確認しchildDiv2ます。

$('.txtClass')

このセレクターは 1 つのアクションのみを実行します。クラスを持つすべての要素を見つけるtxtClass

css-tricks.com のこの記事をご覧ください。

于 2012-07-28T07:24:26.977 に答える