使用optgroups和lodash动态创建选项

时间:2015-02-01 17:23:23

标签: javascript jquery underscore.js lodash

我尝试使用像这样的optgroup创建动态创建的选项:

_.each( _.groupBy(productsCollection.toJSON(), 'menuname'), function( menuname, i ){

  $('#slcproduct').append($("<optgroup>").attr("label",i));

   _.each( menuname, function( product ){
        $('#slcproduct').append($("<option></option>").attr("value", product.id).text(product.product_title));
   });

   $('#slcproduct').append("</optgroup>");
});

因此,我的选项是使用optgroups正确创建的,但选项不是optgroups的子元素。如何将选项附加到optgroups元素中? 非常感谢

1 个答案:

答案 0 :(得分:1)

试试这个:

_.each(_.groupBy(productsCollection.toJSON(), 'menuname'), function(menuname, i) {
  var $optgroup = $("<optgroup>").attr("label", i);
  _.each(menuname, function(product) {
    $optgroup.append($("<option>").attr("value", product.id).text(product.product_title));
  });
  $('#slcproduct').append($optgroup);
});