开发者

How would I write this jQuery in coffeescript?

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

开发者_JAVA百科$.each($(".nested-fields"), function(intIndex) {$(this).find(".set").html(intIndex+1);;} );

Thank you again.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜