我正在编写一个使用jQuery动态创建表单的函数。 由于所选参数不会以任何理由显示,因此我坚持到底。 这是一个Fiddle。
我不认为这是一个大问题,但是我被卡住了。
// Creates select element with N options.
// options is an array with options
// name is the elements ID as a string
// selected, optionally, is the selected option. must be the same type as in options
function make_dynamic_select( options, name, selected ){
select = "<select id='' type='' size ='1', name='" + name + "'>"
options.forEach(function(option){
// a little debug
console.log(typeof option,option," === ",typeof selected,selected,(option === selected))
// append the option
select += (option === selected)? "<option selected>":"<option>" + option + "</option>"
});
return select += "</select>"
};
答案 0 :(得分:1)
您没有正确生成字符串。
使用
select += (option === selected ? "<option selected>":"<option>" ) + option + "</option>";
答案 1 :(得分:0)
这是DEMO。
function make_dynamic_select( options, name, selected ){
select = "<select id='' type='' size ='1', name='" + name + "'>"
options.forEach(function(option){
console.log(typeof option,option," === ",typeof selected,selected,(option === selected))
console.log(option === selected)
select += (option === selected)? "<option selected>"+option+"</option>":"<option>" + option + "</option>"
})
select += "</select>"
return select
};
$("#foo").append(make_dynamic_select([1,2,3],"bar",2));