如何用 CoffeeScript 重写 JS

How to rewrite JS with CoffeeScript

我在JS中有这样的代码:

$('.slider-for').find('img').each(function(){
  var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
  $(this).addClass(imgClass);
})

并且需要在 Coffee 中重写它。这就是我得到的:

$('.slider-cover-photo img').each ->
  imgClass = if $(this).width / $(this).height > 1 then 'wide' else 'tall'
  $(this).addClass imgClass

this 这是一个正确的元素。但是当我尝试获取它的宽度或高度时,它的值为 0 ($(this).width = 0)

问题是您在 coffeescript 中使用的是 $(this).width$(this).height 而不是 this.widththis.height

$('.slider-for').find('img').each ->
   imgClass = if this.width / this.height > 1 then 'wide' else 'tall'
   $(this).addClass imgClass

您也可以在 Coffeescript

中使用 @ 而不是 this

我建议使用 http://js2.coffee/,它非常适合将 js 转换为咖啡或将咖啡转换为 js。本站return咖啡脚本针对你的js

$('.slider-for').find('img').each ->
  imgClass = if @width / @height > 1 then 'wide' else 'tall'
  $(this).addClass imgClass
  return 

N.B -> 不要总是相信自动转换。至少尝试自己阅读输出。