动态创建select字段- >selected<选项没有显示
Create select field dynamically - >selected< option doesn't show up
我正在用jQuery编写一个动态创建表单的函数。现在我在due卡住了选中的参数由于某种原因不会显示出来。这是小提琴
我不认为这是一个大问题,但是我被卡住了。
// 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>"
};
您没有正确生成字符串。
使用select += (option === selected ? "<option selected>":"<option>" ) + option + "</option>";
演示这是一个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));
相关文章:
- 根据所选选项显示/隐藏不同的表单
- HTML 表单字段根据从下拉列表中选择的选项显示/隐藏
- 根据所选选项显示文本
- 禁用浏览器自动选项(显示输入元素中保存的单词)
- 基于所选选项显示asp:TextBox的JavaScript
- 更改选项显示当前时间
- 根据下拉列表中的选定选项显示详细信息
- 如何根据选中的选项显示文本数组
- 根据单独选择的选项显示 HTML 选项
- jQuery不能基于选择选项显示/隐藏元素
- Javascript cookie 用于保存用户首选项并使用共享首选项显示内容
- 根据选择框中的选项显示单选按钮
- 如何在asp.net web应用程序中使用javascript根据下拉列表中选择的选项显示不同的输入类型
- 下拉选项应根据上一个选项显示
- jQuery:根据所选选项显示/隐藏元素
- 选择选项显示/隐藏IE9问题
- 为'
- 我的下拉选项显示按钮时,它不应该'
- 根据选择的选项显示一个Div(带有计算值)——Angular
- 根据带有自定义值属性的选择选项显示图像