admin管理员组

文章数量:1200358

Just trying to learn and confused on how to do the following. Thanks!

$.each($(".nested-fields"), function(intIndex) {$(this).find(".set").html(intIndex+1);;} );

Thank you again.

Just trying to learn and confused on how to do the following. Thanks!

$.each($(".nested-fields"), function(intIndex) {$(this).find(".set").html(intIndex+1);;} );

Thank you again.

Share Improve this question edited Sep 15, 2011 at 12:05 Arnaud Le Blanc 99.9k24 gold badges211 silver badges196 bronze badges asked Sep 15, 2011 at 12:00 Daniel FischerDaniel Fischer 3,0621 gold badge28 silver badges50 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 20

The original javascript could (or should) be written like this:

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

so

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

a more readable version could look like this:

fields = $('.nested-fields')

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

or

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

(This iterates over the array with a for (;;) loop.)

Or if you want to use $.each:

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

BTW the title is a little incorrect; should be how to write this Javascript in Coffeescript ;)

Personally I like the for .. in .. of coffeescrip but I was boring using the following structure to have the iterator as JQuery object :

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

So I defined a items function available to each JQuery object:

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

Now the navigation with coffeescript is simpler :

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

本文标签: javascriptHow would I write this jQuery in coffeescriptStack Overflow