每天一剂Rails良药之八十八:级联选择

javascripts_controller.rb
def dynamic_states
  @states = State.find(:all)
end


application_helper.rb
def javascript(*files)
  content_for(:head) { javascript_include_tag(*files) }
end

def stylesheet(*files)
  content_for(:head) { stylesheet_link_tag(*files) }
end


people/new.html.erb
<% javascript 'dynamic_states' %>


javascripts/dynamic_states.js.erb
var states = new Array();
<% for state in @states -%>
  states.push(new Array(<%= state.country_id %>, '<%=h state.name %>', <%= state.id %>));
<% end -%>

function countrySelected() {
  country_id = $('person_country_id').getValue();
  options = $('person_state_id').options;
  options.length = 1;
  states.each(function(state) {
    if (state[0] == country_id) {
      options[options.length] = new Option(state[1], state[2]);
    }
  });
  if (options.length == 1) {
    $('state_field').hide();
  } else {
    $('state_field').show();
  }
}

document.observe('dom:loaded', function() {
  countrySelected();
  $('person_country_id').observe('change', countrySelected);
});


Prototype的代码,嘿嘿,都很简单
但是,countrySelected方法这样写性能会very very bad,正在做的产品中有切身体会啊
循环上千条数据就能让IE7挂掉哦~Trimpath(JS Template)性能也不咋地哦~

你可能感兴趣的:(JavaScript,虚拟机,Ajax,浏览器,Rails)