Rails 4 - 咖啡脚本无法正常工作

时间:2014-04-09 14:09:27

标签: javascript ruby-on-rails ruby-on-rails-4 coffeescript

目标是在点击时更改图标。这是一个简单的竖起大拇指的评论图标。

显示文件

<a data-method="put" data-remote="true" href="/comments/1/like" rel="nofollow">

  <img alt="" src="/assets/othericons/thumbsup_off.PNG" 
  style="height: 20px; width: 20px" id="imgClickAndChange" onclick="changeImage()"  />

</a>

的CoffeeScript

$("#imgClickAndChange").click ->
  imagePath = $("#imgClickAndChange").attr("src")
  if imagePath is "/assets/othericons/thumbsup_off.PNG"
    $("#imgClickAndChange").attr "src", "/assets/othericons/thumbsup_on.PNG"
  else
    $("#imgClickAndChange").attr "src", "/assets/othericons/thumbsup_off.PNG"
  return

aplication.js文件

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require jquery.ui.all
//= require jquery.turbolinks
//= require jquery-simple-pagination-plugin
//= require jquery.raty
//= require_tree .

1 个答案:

答案 0 :(得分:1)

我建议你使用这段代码:

<img alt="" src="/assets/othericons/thumbsup_off.PNG" 
  style="height: 20px; width: 20px" id="imgClickAndChange" onclick="window.changeImage($(this))"  />

:coffeescript
  window.changeImage = (source) ->
    console.log "called changeImage(source)"
    $source = $(source)
    imagePath = $source.attr("src")
    if imagePath && imagePath == "/assets/othericons/thumbsup_off.PNG"
      console.log "thumbsup is currently OFF"
      $source.attr("src", "/assets/othericons/thumbsup_on.PNG")
    else
      console.log "thumbsup is currently ON"
      $source.attr("src", "/assets/othericons/thumbsup_off.PNG")

您应该会在控制台中看到消息(f12适用于Google Chrome浏览器,选项卡&#39;控制台&#39;),如果您没有看到这些消息,那么您的JavaScript / Coffeescript就会出现问题

一点建议:重命名你的js函数&#34; changeImage()&#34; to&#34; toggleImage()&#34;,为什么?因为此功能实际上是在两个图像之间切换(不少于,不多于)。

希望这有帮助!