【问题标题】:How to rewrite JS with CoffeeScript如何用 CoffeeScript 重写 JS
【发布时间】:2017-10-04 23:20:04
【问题描述】:

我在 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)

【问题讨论】:

  • 为什么在你的 JavaScript 中使用 this.width 而在 CoffeeScript 中使用 $(this).width

标签: javascript css coffeescript


【解决方案1】:

问题是您在咖啡脚本中使用$(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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-09-06
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      相关资源
      最近更新 更多