javascript - 如何用 CoffeeScript 重写 JS

标签 javascript css 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

关于javascript - 如何用 CoffeeScript 重写 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43822509/

相关文章:

javascript - 消除渲染阻塞 JavaScript 和 CSS

jquery - 修复 jQuery block 元素动画

html - 具有空白元素的父元素的 CSS 选择器

jquery - 尝试将一个切换应用到多个 div

ruby-on-rails - Ruby on Rails 无法使用 CoffeeScript 和 AJAX 发送获取请求

javascript - Coffeescript:替换 <img> src 属性

javascript - 如何一次将多个样式表和 Bootstrap 库导入到一个 HTML 文档中?

javascript - 当我提交文本时,它不会离开文本区域

javascript - 为什么 hr 标签的 CSS 不会出现在 React 代码中?

javascript - 我们可以使用键控函数的对象在运行时定义类吗?