动态创建select字段- >selected<选项没有显示

Create select field dynamically - >selected< option doesn't show up

本文关键字:选项 显示 selected 创建 select 字段 动态      更新时间:2023-09-26

我正在用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));
相关文章: