【问题标题】:Rails 4: coffeescript conditional display based on select field valueRails 4:基于选择字段值的咖啡脚本条件显示
【发布时间】:2016-03-06 03:30:18
【问题描述】:

在我的 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>

现在,我需要在页面上显示特定消息,在 &lt;div id="post_format_analysis"&gt;&lt;/div&gt; 内并实时(无需重新加载页面),具体取决于用户选择的选项。

所以,我在我的 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'

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

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

我认为问题在于我用$(document).ready -&gt; 初始化代码,而当#post_format div 的值发生变化时我也应该初始化它,但我不知道如何使它工作。

有什么想法吗?

【问题讨论】:

  • 将 if else 包装在更改事件绑定中。 $('#post_format').on 'change', -&gt;
  • 谢谢,这行得通。有没有办法在页面加载时也考虑选择的值,所以即使用户第一次加载页面时也会显示正确的消息,而不仅仅是在他选择不同的值时?可能是$('#post_format').on 'load, change', -&gt; 之类的?
  • 或者preventDefault 可能?
  • 绑定后直接调用$('#post_format').change()
  • 酷,谢谢。随时提供此解决方案作为答案,我很乐意接受。

标签: ruby-on-rails ruby-on-rails-4 drop-down-menu coffeescript conditional


【解决方案1】:

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

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

    .trigger('change')

【讨论】:

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