【问题标题】:jQuery show method not working in rails appjQuery show 方法在 Rails 应用程序中不起作用
【发布时间】:2016-09-21 23:43:27
【问题描述】:

(这里是 jQuery/Javascript 新手)

在我的 rails 应用程序中,我试图查看下拉菜单中的选定选项是否与文本“新类别”匹配,如果是,那么我想要一段 html 来为表单显示一个新行用户可以指定一个新的类别名称。

在我的 class.coffee 文件中,我有这个:

$(document).on "turbolinks:load", ->
  if( $('#category-select option.selected').text() == "New Category")
    $('#new-categrory').show()

在我的 class.html.erb 文件中,我有这个:

<div class="col-xs-6 center block">
            <%= f.label :category, "Category" %>
            <%= f.select :category, options_for_select(getAllCategories), {}, {:required => true, :class => 'form-control', id: "category-select"} %>
            <%= f.text_field :category, :class => 'form-control', id: "new-category" %>
</div>

(我的 getAllCategories 函数只返回一个选项数组,但这并不重要)

最后,我的 class.scss 中有一个班级规则:

#new-category{
display: none;
}

所以我很困惑。我已经尝试使用来自多个 stackoverflow 问题的语法,但没有任何效果。

在选择下拉时,我已经能够运行一个简单的警报弹出窗口,所以我知道jQuery正在运行。

任何帮助将不胜感激。

【问题讨论】:

    标签: jquery coffeescript ruby-on-rails-5


    【解决方案1】:

    您的咖啡脚本文件中的缩进可能是问题所在,请尝试将第二行缩进一级,例如:

    $(document).on "turbolinks:load", ->
      if( $('#category-select option.selected').text() == "New Category")
        $('#new-categrory').show()
    

    Here is a link showing the issue with what you have now ---- NOTE: had use a weird link shortener because the coffeescript compiler was generating url that didn't mesh nicely with markdown.

    【讨论】:

    • 它在我的代码中是缩进的,当我复制它时它没有正确显示
    【解决方案2】:

    我想出了怎么做。

    '#select-category' id 更改后我就运行它,所以

    $(document).on "turbolinks:load", ->
        $('#category-select').change ->
            selected = $('#category-select').val()
            if selected is "New Category"
                $('#new-category').show()
            else
                $('#new-category').hide()
    

    这终于成功了。希望可以帮助其他遇到此问题的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 2010-10-21
      • 1970-01-01
      • 2016-03-20
      相关资源
      最近更新 更多