用于根据提供的值生成选择标记的Javascript帮助方法

时间:2010-12-27 05:40:13

标签: javascript html

我正在尝试在我的JS工具包中创建一个看起来像这样的辅助方法

var selectOptionValues = [" ","NA","Yes","No"];
var selectedValue = "No";


function CreateSelectList(selectId,selectOptionValues,selectedValue){
// build the selectlist
// if the selectedValue is not null make this value selected
// return select tag
}

我尝试执行类似selectedOption = selectTag[selectedValue]然后selecteOption.selected = true的操作,但它不起作用。

2 个答案:

答案 0 :(得分:3)

假设您通过创建DOM节点和不起作用的部分生成选项,则选择No选项的状态。尝试selectOption.setAttribute(“selected”,“selected”) - 粗略......

var selectOptionValues = [" ","NA","Yes","No"], selectedValue = "No";

function CreateSelectList(selectId,selectOptionValues,selectedValue){
    var selectList = document.createElement("select"), selectOption;
    for (var i=0, totalOptions = selectOptionValues.length; i < totalOptions ; i++) {
        selectOption = document.createElement("option");
        selectOption.value = selectOptionValues[i];
        selectOption.innerText = selectOptionValues[i];
        if (selectOptionValues[i] == selectedValue) {
            selectOption.setAttribute("selected","selected");
        }
        selectList.appendChild(selectOption);
    };
    return selectList;
}

答案 1 :(得分:1)

除了Dean Burge建议的方法,您还可以通过select对象的selectedIndex属性设置默认值。如果使selectedValue成为所需值的索引,则变得非常简单:

//selectedValue==3;
yourPopulatedSelect.selectedIndex=selectedValue;
//"No" will be selected