0

私はJSONオブジェクトを持っています:

    var data = {"options" :[      
       {"name": "Size",  "value": "S", "price": "10", "order": "1"},
       {"name": "Size",  "value": "M", "price": "12", "order": "2"},
       {"name": "Size",  "value": "XL", "price": "14", "order":"3"},
       {"name": "Color", "value": "Red", "price": "14", "order":"2"},    
       {"name": "Color", "value": "Green", "price": "12", "order": "1"}
    ]}

mootools javascript ライブラリを使用してこれを選択リストに変換するにはどうすればよいですか?

<div>
 <label>Size:</label>
 <select name="options[size]">
   <option value="10">S</option>
   <option value="12">M</option>
   <option value="14">XL</option>
 </select>
 <label>Color:</label>
 <select name="options[color]">
   <option value="12">Green</option>
   <option value="14">Red</option>
 </select>
</div>

ありがとう!

4

1 に答える 1

1

データを少しいじっているだけです-そこに行きます: http://jsfiddle.net/XRH6r/

var data = {"options" :[      
       {"name": "Size",  "value": "S", "price": "10", "order": "1"},
       {"name": "Size",  "value": "M", "price": "12", "order": "2"},
       {"name": "Size",  "value": "XL", "price": "14", "order":"3"},
       {"name": "Color", "value": "Red", "price": "14", "order":"2"},    
       {"name": "Color", "value": "Green", "price": "12", "order": "1"}
    ]};

//create unique map according to the data:
var arr = data.options;
var map = {};
arr.each(function(item){
    var name = item.name;
    var o;
    if(map[name]){
       o = map[name];      
    }
    else{
        o = {};
        o.options = [];
        map[name] = o;
    }
  o.options.push({value:item.value,price:item.price,order:Number(item.order)});
});

//sort options array to be ordered by order
//and then build the select
Object.each(map,function(item,name){
    item.options.sort(function(a,b){
           return a.order > b.order;
    });
    var label = new Element('label').set('html',name);
    var combo = new Element('select');
    item.options.each(function(opt){
       combo.options[combo.options.length] = new Option(opt.value,opt.price);     
    });

    label.inject(document.body);
    combo.inject(document.body);
});
于 2013-03-28T14:48:49.813 に答える