JQuery工作,但只有当我重新加载页面时

时间:2013-07-08 08:34:44

标签: jquery ruby-on-rails ruby

我试图在ruby中做动态选择框。 JQuery看起来像这样:

jQuery ->
$('#person_state_id').parent().hide()
states = $('#person_state_id').html()
$('#person_country_id').change ->
 country = $('#person_country_id :selected').text()
escaped_country = country.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
options = $(states).filter("optgroup[label='#{escaped_country}']").html()
if options
  $('#person_state_id').html(options)
  $('#person_state_id').parent().show()
else
  $('#person_state_id').empty()
  $('#person_state_id').parent().hide()

并在视野中:

<%= f.grouped_collection_select :state_id, Country.order(:name), :states, :name, :id, :name, include_blank: true %>

这是工作但是......当我在example.com/person/new上访问我的页面时 - 它不起作用。我必须重新加载页面 - 然后一切正常......为什么它不会在第一次访问时加载JQuery?

2 个答案:

答案 0 :(得分:2)

$(document).ready()内写下您的功能,以加载列表框中的项目 此功能将在页面加载期间加载您的功能

$(document).ready(function() {
  //your function;
});

答案 1 :(得分:0)

正如Ian所述,

在Rails 4.0中,只需将其添加到您的Gemfile:

  

gem'jquery-turbolinks'

这是你的assets / javascripts / application.js文件:

  

// = require jquery.turbolinks

相关问题