0
$('.row').slice(0, 3).css('background-color: green');
$('.row').slice(4, 6).css('background-color: yellow');
$('.row').slice(6, 10).css('background-color: green');

或者

x = 0;
$('.row').each(function() {
   if (x >= 0 && x <= 3) {
      $(this).css('background-color: green');
   }
   if (x >= 4 && x <= 6) {
      $(this).css('background-color: yellow');
   }
   if (x >= 6 && x <= 10) {
      $(this).css('background-color: green');
   }
   x++;
});

一个比另一个快吗?

4

2 回答 2

4

使用切片。每个都在每次迭代时进行比较。切片将只占用列。加上 slice 更好地表达了意图 - 这将允许更好的优化(如果有的话)并且代码更具可读性。

于 2012-05-10T22:38:43.037 回答
0

完全使用您的示例并主要考虑性能,纯 css 解决方案可能更快:

.row:nth-child(-n+10) { background-color: green; }
.row:nth-child(-n+6)  { background-color: yellow; }
.row:nth-child(-n+3)  { background-color: green; }

顺序看起来颠倒了,但它的作用是:首先将前 10 名中的所有 10 项变为绿色,然后将前 6 项变为黄色,然后再次将前 3 项变为绿色。

但这仅适用于静态 html。如果您正在动态更改选择,那么确实使用 jquery.slice。

于 2013-07-10T15:37:03.890 回答