【问题标题】:Coffeescript If works, but Else does notCoffeescript 如果有效,但 Else 无效
【发布时间】:2013-09-19 06:26:54
【问题描述】:

这是视图调用的部分:

<li>
  <span class="content"><%= link_to "#{key.name} (#{key.description})", key %> (<%= key.id %>)</span>
  <span class="timestamp">
    Created <%= time_ago_in_words(key.created_at) %> ago.
  </span>
  <span class="content">
  <% if key.chords.count > 0 %>
    <%= link_to "show chords", '#', class: "showremovechords" %>
    <span> // </span>
  <% end %>
      <%= link_to "remove", key, method: :delete %>     
  </span>
  <div class="chordsholder">
    <ol class="chords">
    <% if key.chords.count > 0 %>
      <ol class="microposts">
        <%= render key.chords %>
      </ol>
    <% end %>
    </ol>
    </div>
</li>

这是 jQuery(使用 CoffeeScript),当点击“显示和弦”按钮时,它会切换是否显示 div class= 'chordsholder'。

jQuery ->
  toggleChords = (e) ->
    e.preventDefault()
    if $(@).text('show chords')
        $(@).text('hide chords')
    else
        $(@).text('show chords')
    $(@).closest('li').find('.chordsholder').slideToggle()

  $('.showremovechords').click toggleChords

div 开始隐藏,链接以文本“show chords”开头

div 可见性的切换有效,第一次单击时文本变为“隐藏和弦”,但语句的 ELSE 部分不起作用,因此在第一次单击时文本不会变回“显示和弦” div 是隐藏的。任何想法为什么会发生这种情况? 谢谢

【问题讨论】:

    标签: jquery ruby-on-rails coffeescript


    【解决方案1】:

    在您的代码中:

    if $(@).text('show chords')
    

    设置值,表达式的返回值总是truthy。所以你的 else 永远不会执行。 jqobject.text(something) 是二传手。相反,您可能想要比较值.. 所以这里发生的是,由于 if 条件中的设置器,它会将值设置为“显示绳索”,然后返回 jquery 对象,它是 truthy 所以它转到你的 if 块,然后将其设置为“隐藏线”。

    试试

    if $(@).text() === 'show chords'
            $(@).text('hide chords')
    else
        $(@).text('show chords');
    

    您也可以使用文本的 fn 参数语法来执行此操作(但不确定咖啡语法)。

    $(@).text(function(_, curValue){
       return curValue === 'show chords' ? 'hide chords' : 'show chords';
    })
    

    【讨论】:

    • 太棒了,谢谢!仅供参考,coffeescript 中没有三元运算符。再次感谢!
    • 但是你可以用if curValue is 'show chords' then 'hide chords' else 'show chords'一行来完成!
    猜你喜欢
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 2012-05-08
    • 2017-03-15
    • 2014-10-30
    • 2011-03-08
    相关资源
    最近更新 更多