【问题标题】:Rails 4 - coffee script not working properlyRails 4 - 咖啡脚本无法正常工作
【发布时间】:2014-05-22 19:30:04
【问题描述】:

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

显示文件

<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>

咖啡脚本

$("#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 .

【问题讨论】:

  • 你有一个 jquery 方法和一个 onclick 方法,都用于点击?为什么?也许删除其中一个
  • 你有什么建议?我尝试删除 onlick="...",但同样的问题仍然存在。
  • 不正常,点击功能执行成功了吗?
  • 没有。当我点击它时,图像不会改变。我尝试了不同的脚本,但我认为问题可能出在 rails 代码的其他地方。

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


【解决方案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")

您应该会在控制台中看到消息(Google Chrome 浏览器的 f12,选项卡“控制台”),如果您没有看到任何这些消息,则说明您的 JavaScript/Coffeescript 有问题。

一个小建议:将你的 js 函数“changeImage()”重命名为“toggleImage()”,为什么?因为这个函数实际上是在 2 张图像之间切换(不是更少,不是更多)。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2017-01-07
    • 2012-02-08
    • 1970-01-01
    • 2018-01-25
    • 2015-08-03
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    相关资源
    最近更新 更多