2011-09-15 28 views

回答

20

原來的JavaScript可以(或應該)這樣寫:

$('.nested-fields').each(function(i){ 
    $(this).find('.set').html(i+1) 
}) 

所以

$('.nested-fields').each (i) -> 
    $(this).find('.set').html i+1 

一個更可讀的版本可以看起來像這樣:

fields = $('.nested-fields') 

for field, i in fields 
    set = $(field).find('.set') 
    set.html i+1 

$(field).find('.set').html i+1 for field in fields 
+0

對於$()。每個:)都很好(每個:)('.html i + 1 for field in fields'不是*那*更具可讀性)我會至少使用'.html(i + 1)' – arnaud576875

+0

我喜歡最後一個,但是我會盡全力在$('。nested-fields')'中爲字段創建'。我同意@arnaud:'.html(i + 1)'更容易閱讀。 – 2011-09-15 22:55:03

3
for field, i in $(".nested-fields") 
    $(field).find('.set').html(i+1) 

(這迭代用的(;;)循環陣列上。)

或者,如果你想使用$。每個:

$.each $(".nested-fields"), (i) -> 
    $(this).find('.set').html(i+1) 

BTW標題是有點不正確;應該如何的CoffeeScript寫此Javascript;)

0

個人我喜歡coffeescrip的for .. in ..但我用的是以下結構具有迭代器作爲jQuery對象鏜:

for td in $('td.my_class') 
    $td = $(td) 
    .. 

因此,我所定義的項每個JQuery的目標函數可用:

$.fn.items = -> $.map(this, $) 

現在用CoffeeScript的導航更簡單:

for $td in $('td.my_class').items() 
    $td <-- is a JQuery object