【问题标题】:Unique action for individual item in .each( ).each( ) 中单个项目的唯一操作
【发布时间】:2012-05-30 22:37:06
【问题描述】:

是否可以在 .each() 函数中为每个结果编写单独的代码?

我想在the example 中做的是让每个订单项都有一个独特的颜色。这可以在 .each() 中完成吗?

$(document).ready(function() {    
    $('li').each(function() {
        $(this).css('color', 'purple');
    }); 
// End it all    
});​

http://jsfiddle.net/rJGYL/

编辑:为了更简洁,是否可以为每个项目添加唯一的 css?例如,不仅仅是一种颜色,而是说我想让第一项的字体粗体为粗体,下一项为斜体...

【问题讨论】:

  • 关于您的编辑:想法是一样的。创建一个具有 CSS 属性的对象数组,并通过它们的索引将它们应用于元素。
  • 是的,通过使用 CSS。如果您不希望立即显示唯一的 css,您可以使用 jQuery 将一个激活器类添加到某个父级,以激活您在 css 文件中声明的所有唯一 css
  • 检查我的更新答案。您也可以指定其他 css 值。 :)

标签: jquery each


【解决方案1】:
$(document).ready(function() {

var colors = ['red','green', 'blue', 'pink']

    $('li').each(function(i) {
        $(this).css('color', colors[i]);
    });


// End it all    
});​

JSFiddle:http://jsfiddle.net/lucuma/aU4kr/

您可以使用每个函数中的索引来引用数组。如果您想了解更多详细信息,可以在这里找到:http://api.jquery.com/each/

【讨论】:

  • 或更简洁:$('li').css('color', function(i) { return colors[i]; }).
  • 如果这是使用 .css() 回调版本的答案,我会 +1 Felix
【解决方案2】:

是的,您可以使用以下代码来完成此操作

$(document).ready(function() {
  var colors = ['black','red','purple','yellow']
    $('li').each(function(i) {
        $(this).css('color', colors[i]);
    });


// End it all    
});​

Working Fiddle

将您的颜色放入colors 数组中。

更新

您可以像这样为数组中的每个 li 定义不同的 css

$(document).ready(function() {
    var css = [{'font-weight':'bold','font-size':'25px','color':'red'}
               ,{'color':'purple'},{'color':'black'},{'color':'yellow'}]
    $('li').each(function(i) {
        $(this).css(css[i]);

    });


// End it all    
});​

Working Fiddle

您已在 css 对象数组中将 css 属性定义为 'key':'value' 对。

【讨论】:

  • 这比它必须的要复杂。您可以将对象直接传递给css$(this).css(css[i])。无需遍历属性。
  • thnx,我不知道。更新答案。 :)
【解决方案3】:

您可以指定一个可用颜色的数组,然后使用每个项目的索引从该数组中选择:

http://jsfiddle.net/rJGYL/2/

$(document).ready(function() {
    var colors = ["purple", "red", "blue", "yellow"];

    $('li').each(function(index) {
        $(this).css('color', colors[index]);
    });


    // End it all    
});​

【讨论】:

    【解决方案4】:
    var colors= ['red','green', 'blue'];
    
    $('li').css('color', function() {
        return colors[i];
    });
    

    【讨论】:

      猜你喜欢
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多