4

基于对另一个我的问题的回答(这个:How to make children auto fit 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() 和兄弟姐妹():

$("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

我会预先查询元素,如下所示:

// 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 回答
3

使用FireBug 分析

  • 块 1:8.466 毫秒,372 次调用
  • 块 2:10.130 毫秒,526 次调用
  • 块 3:8.560 毫秒,383 次调用

xixonia的回答也是最快的

  • xixonia:8.205 毫秒,369 次通话

按速度排序:

  1. xixonia的
  2. 区块 1
  3. 块 3

甚至不会使用块 2

于 2011-05-02T16:46:46.823 回答
0

我会说Block 1最好,因为它不需要循环,

你也可以试试这个:

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