如何让eq影响所有实例,而不仅仅是第一个实例?

时间:2013-09-15 21:19:16

标签: jquery ruby-on-rails coffeescript

我在包含标签和5个选择的div上有一个名为datetimeselect的类。我想为每个选择设置自定义宽度。但是,我写的coffeescript只会影响该类的第一个div而不影响该类的其余div。如何让我的代码使用类datetimeselect来影响所有div?

我的咖啡:

jQuery ->

    a = [75, 110, 60, 80, 60]

    $(".datetimeselect").children('select').eq(0).css("width", a[0])

    $(".datetimeselect").children('select').eq(1).css("width", a[1])

    $(".datetimeselect").children('select').eq(2).css("width", a[2])

    $(".datetimeselect").children('select').eq(3).css("width", a[3])

    $(".datetimeselect").children('select').eq(4).css("width", a[4])

html / erb代码:

<div class="well datetimeselect">
    <%= f.label :time_start, "Time Start:" %> 

    <%= f.datetime_select :time_start, ampm: true, :class => "field span1" %>
</div>

<div class="well datetimeselect">
    <%= f.label :time_end, "Time End:" %> 

    <%= f.datetime_select :time_end, default: 1.days.from_now, ampm: true, :class => "field span1" %>
</div>

2 个答案:

答案 0 :(得分:1)

根本不要使用.eq()。请改用.each()

$(".datetimeselect").each(function(idx, el) {
    $(el).children("select").css("width", a[idx % a.length]);
});

答案 1 :(得分:1)

您可以使用.css()回调函数:

$(".datetimeselect > select").css('width', function(ind) {
   return a[ind];
});

CoffeeScript的:

$(".datetimeselect > select").css 'width', (index) -> a[index]