4

別の私の質問 (これ: How to make children auto fit the parent's width only with CSS? ) への回答に基づいて、パフォーマンスに関する問題を解決するための最良の jQuery アプローチはどれかを考えています。

ブロック 1: 必要に応じてすべての DOM 要素を検索します。

$("div.parent a").css("width", $("div.parent").width() / $("div.parent a").length - 2);

ブロック 2: DOM の子のみを検索し、each()、parent()、および siblings() を使用します。

$("div.parent a").each(function() {
    $(this).css("width", $(this).parent().width() / $(this).siblings().length - 2);
});

ブロック 3: 最初に DOM の親を見つけ、each() を使用して、コンテキストに基づいて子を見つけます。

$("div.parent").each(function() {
    $("a", this).css("width", $(this).width() / $("a", this).length - 2);
});

誰かがテストしたい場合のフィドルは次のとおりです。http://jsfiddle.net/ErickPetru/6nSEj/3/

では、どのブロックが良いでしょうか?なぜ?

4

3 に答える 3

3

FireBug プロファイリングの使用:

  • ブロック 1: 8.466 ミリ秒、372 コール
  • ブロック 2: 10.130 ミリ秒、526 コール
  • ブロック 3: 8.560 ミリ秒、383 コール

また、xixoniaの回答が最速でした

  • xixonia: 8.205 ミリ秒、369 コール

速度の順に:

  1. クシソニアズ
  2. ブロック 1
  3. ブロック 3

ブロック2すら使わない

于 2011-05-02T16:46:46.823 に答える
3

次のように、要素を事前にクエリします。

// find the elements you want to resize
var $links = $("div.parent a");

// resize them, and use the parent width
$links.width($links.parent().width() / $links.length - 2);

このようにして、リンクを検索し、親を検索するのは一度だけです。ループはなく、冗長なクエリもありません。

次に例を示します。

http://jsfiddle.net/xixionia/Gsek5/

于 2011-05-02T16:07:21.990 に答える
0

ループを必要としないBlock 1という事実のために最善だと思いますが、

これを試すこともできます:

$("div.parent a").css({
    width: $(this).parent().width() / $(this).siblings().length - 2)
});
于 2011-05-02T15:39:38.487 に答える