我在 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.width
和 this.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/