“ } ]};var select =“”;
VAR MAPINFO </跨度> = function(element,info){ $ .map(info,function(val,num){的console.log(VAL); })}
var generateSelector = function(info){
选择“+ +”&lt; select’+ info.id +‘&gt;&lt; / select&gt;’ 选择+ = MAPINFO </跨度> (选择,info.options)
$( ‘主体’)追加(选择)。
}(宾语);
jsfiddle在这里 鈥
这是我的发电机版本。 :)
$(object).each(function(i,v) { var label = $("<label />", { html: v.label, 'for': v.name }); var element; switch(v.type) { case "select": element = $("<select />", { id: v.id, name: v.name }); $(v.options).each(function(x,y) { var option = $("<option />", { value : y.value, html : y.text }); element.append(option) }); break; } $("body").append(label, element); });
[看到它在行动]
$(document).ready(function () { var jsonObject = { "id": "countries", "label": "Country", "name": "countries", "type": "select", "options": [ { "value": "", "text": "Select Country" }, { "value": "in", "text": "India", "selected": "true" }, { "value": "us", "text": "United Stated" }, { "value": "uk", "text": "United Kingdom" }, { "value": "cn", "text": "Canada" } ] }; var selectedvalue = ''; $("body").append($("<label />", { html: jsonObject.label, 'for': jsonObject.name }), $("<select id='ddlSelect' />", { id: jsonObject.id, name: jsonObject.name }).html($.map(jsonObject.options, function (entity, i) { if (entity.selected == "true") selectedvalue = entity.value; return '<option value="' + entity.value + '">' + entity.text + '</option>'; //return $("<option />", { value: entity.value, text: entity.text }); }).join(''))); $('#ddlSelect').val(selectedvalue).trigger('change'); });
对于演示,请看到此链接: http://jsfiddle.net/nanoquantumtech/vUwVq/
试试这个
function generateSelector(obj) { var selector = $('<div></div>'); var label = $('<label for="' + obj.id + '">' + obj.label + '</label>'); var selectElem = $('<select id="' + obj.id + '" name="' + obj.name + '"></select>'); for (var i = 0; i < obj.options.length; i++) { var option = $('<option value="' + obj.options[i].value + '">' + obj.options[i].text + '</option>'); if (obj.options[i].selected) option.attr('selected', 'selected'); option.appendTo(selectElem); } label.appendTo(selector); selectElem.appendTo(selector); return selector;
}