Rails4:coffeescript根据select字段值条件显示

Rails 4: coffeescript conditional display based on select field value

在我的 Rails 4 应用程序中,我有以下表格(与我的 Post 模型相关):

<div class="field">
  <%= f.label :format, "FORMAT" %>
  <%= f.select :format, ['A', 'B', 'C', 'D'] %>
</div>

呈现以下 html 代码:

<div class="field">
  <label for="post_format">FORMAT</label>
  <select name="post[format]" id="post_format">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    <option value="D">D</option>
</div>

现在,我需要根据用户选择的选项,在页面上 <div id="post_format_analysis"></div> 实时显示特定消息(无需重新加载页面)。

所以,我在 posts.coffee 文件中尝试了这个:

$(document).ready ->
  post_format = document.getElementById("post_format")
  if post_format.options[post_format.selectedIndex].value == 'A'
    $('#post_format_analysis').html 'GREAT'
  else if post_format.options[post_format.selectedIndex].value == 'B'
    $('#post_format_analysis').html 'GOOD'
  else if post_format.options[post_format.selectedIndex].value == 'C'
    $('#post_format_analysis').html 'OK'
  else if post_format.options[post_format.selectedIndex].value == 'D'
    $('#post_format_analysis').html 'BAD'

问题是,这只在第一次加载页面时有效,即:消息 (GREAT) 对应于默认选择的值 ( A) 显示。

但是,当用户选择另一个值时,消息不会更新。

我认为问题是我用 $(document).ready -> 初始化代码,而当 #post_format div 的值发生变化时我也应该初始化它,但我是不确定如何进行这项工作。

有什么想法吗?

代码的问题是它没有观察到 select 字段值的变化。您可以通过将整个代码放在更改事件绑定回调中来实现这一点。我还建议进行小规模重构,让您的代码看起来更简洁。

$(document).ready ->
  $('#post_format')
    .on 'change', ->
      grades = { 'A': 'GREAT', 'B': 'GOOD', 'C': 'OK', 'D': 'BAD' }
      $('#post_format_analysis').html grades[@value]

    .trigger('change')