无法在Rails应用程序中获取jQuery .change()事件

时间:2015-10-11 23:05:44

标签: javascript jquery ruby-on-rails coffeescript turbolinks

所以我一直在阅读如何让jQuery和Turbolinks在几个小时内很好地一起玩,我仍然无法启动.change()。我添加了jquery-turbolinks gem无济于事。这是我的CoffeeScript:

$(document).ready ->
  $("#data_type").change ->
    dt = $("#data_type").val()
    switch dt
      when "radio" then $("#radio_conditional").show()
      when "checklist" then $("#checklist_conditional").show()
      when "integer", "decimal"
        $("#units_conditional").show()
        $("#length_conditional").show()
      else $("#radio_conditional", "#checklist_conditional", "#units_conditional", "#length_conditional").hide()
  return
return

基本上我希望表单上的某些字段仅在为选择器#data_type选择某种数据类型时显示。我认为$(document).ready正在工作,但是当我改变数据类型时没有任何反应,无论我选择哪种类型。我知道jQuery正在工作,因为我可以在控制台中输入$(" #radio_conditional")。hide()并且它可以工作。我有一种感觉,我在这里错过了一些简单的东西,但我无法弄明白。有任何想法吗?

这是我的application.js:

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap-sprockets
//= require nested_form_fields
//= require turbolinks
//= require_self
//= require_tree .
//= stub pages

这是我的Gemfile:

source 'https://rubygems.org'
ruby "2.2.3"

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.4'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Turbolinks also screws up jquery. This gem fixes it.
gem 'jquery-turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use figaro for setting environment variables
gem 'figaro'

# Use simple_form for forms
gem 'simple_form'

# Use nested_form_fields to create forms for nested associations
gem 'nested_form_fields'

# Use bootstrap for easy CSS
gem 'bootstrap-sass'

2 个答案:

答案 0 :(得分:0)

尝试将js包装成:

var ready;
ready = function() {

    // your code

$(document).on('page:change', ready);

总是这样做对我来说。

答案 1 :(得分:0)

好的,我明白了。结果我试图选择" #data_type"在页面准备好了,但它实际上并没有存在于页面上,直到我点击"添加变量",因此选择器从未被选中。我点击"添加变量后更改了脚本。"现在全部修好了,谢谢!