繁体   English   中英

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

[英]Rails 4 - coffee script not working properly

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

显示文件

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

我建议您使用以下代码:

<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张图像之间切换(不少于多)。

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM