开发者

jquery .each and rails

I'm trying to translate this script to jQuery. See rails casts #88

var colors = new Array();
<%= for color in @colors %>
  colors.push(new Array(<%= colot.product_id %>, '<%= color.name %>', <%= color.id %>));
<% end %>

function productSelected() {
  product_id = $('order_items_attributes_0_product_id').val();
  options = $('item_color_id').options;
  colors.each(function(color) {
    if (color[0] == product_id) {
      options[options.length] = new Option(color[1], color[2]);
    }
  });
  if (options.length == 1) {
    $('color_field').hide();
  } else {
    $('color_field').show();
  }
}

$(document).ready(function() {
  productSelected();
  $('order_items_attributes_0_product_id').change(productSelected);
});

Firebug says

TypeError: 'undefined' is not a function (evaluating 'colors.each(function(color) {
    if (color[0] == product_id) {
      options[options.length] = new开发者_JAVA百科 Option(color[1], color[2]);
    }
  })')

Also the ruby code is no longer allowed in 3.1.1 js files (under assets)? It also complains about SyntaxError: Unexpected token '<'


Your implementation of .each is wrong. Use:

$.each(colors, function(){

colors is an array, which does not have the JQuery .each method. The $.each function accepts to parameters:

  1. Element to loop through
  2. Function to run at each loop

See also

  • http://api.jquery.com/each/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜