【问题标题】:Rails 4: Upvote/Downvote with coffeescriptRails 4:使用咖啡脚本支持/反对
【发布时间】:2014-04-11 15:00:08
【问题描述】:

它与 stackoverflow 上的类似 - 您可以对评论进行投票,并且当您这样做时,它会用橙色箭头标记。但是,我有 2 个图标(开和关)用于赞成票和 2 个用于反对票。 问题是,当我单击 upvote 时,它​​会将图标更改为“on”,这很好,但是当我在那之后单击 downvote 时,upvote 保持不变(带有 on 图标)。所以,我基本上得到了 2 个“开启”图标。

目标:当您投赞成票/反对票并决定更改投票时,之前选择的图标应为“关闭”

-我当前的代码-

<div class="thumbsup">
    <%= link_to image_tag('othericons/thumbsup_off.PNG', height: '20', width: '20', id: "imgClickAndChange", :onclick => "window.changeImage($(this))"),  like_post_comment_path(comment.post_id, comment), method: :put, :remote => true %>
</div>

<div class="thumbsdown">
  <%= link_to image_tag('othericons/thumbsdown_off.PNG', height: '20', width: '20', id: "imgClickAndChange", :onclick => "window.toggleImage($(this))"), dislike_post_comment_path(comment.post_id, comment), method: :put, :remote => true %>
</div>

咖啡脚本

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

window.toggleImage = (source) ->
    console.log "called changeImage(source)"
    $source = $(source)
    imagePath = $source.attr("src")
    if imagePath && imagePath == "/assets/othericons/thumbsdown_off.PNG"
      console.log "thumbsdown is currently OFF"
      $source.attr("src", "/assets/othericons/thumbsdown_on.PNG")
    else
      console.log "thumbsdown is currently ON"
      $source.attr("src", "/assets/othericons/thumbsdown_off.PNG")

【问题讨论】:

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


    【解决方案1】:

    你会更好地处理来自服务器的数据:

    #app/controllers/votes_controller.rb
    def like
         #your code
         status = "on"
         respond_to do |format|
             format.js { render json: status.to_json }
         end
    end
    
    #same for dislike, except status = "off"
    

    然后您可以使用ajax:success 回调处理图像:

    $(document).on "ajax:success", "#imgClickAndChange", (data) ->
        $(this).attr("src"), "/assets/othericons/thumbsup_"+ data +".PNG")
    

    目前,我什至不知道您的咖啡脚本是如何触发的?它不绑定任何事件?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2014-12-12
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      相关资源
      最近更新 更多