Javascript Option元素's在IE兼容性中选择

Javascript Option element's Select in IE Compatibility

本文关键字:IE 兼容性 选择 Option 元素 Javascript      更新时间:2023-09-26

我正在javascript中动态创建一个选项控件:

我从ajax调用的返回对象填充选项。

我检查结果对象的默认标志,并设置dom对象"select"的"selected"属性。

这很好,除了在兼容模式下结果不一样。

在IE兼容性模式(IE 7)中,该选项具有索引的第一个选择值。

select = document.createElement("select");
                select.id = "tr_theGrid" + i + "_DropDown";
                select.className = "theField"
                select.style.width = "100%";
                for (var x = 0; x < docpreviews.length; x++) {
                    option = document.createElement("option");
                    option.value = docpreviews[x].PrevId;
                    option.innerHTML = docpreviews[x].PrevName;
                    if (m_documents_Merge.DocumentsAttachments[i].Previews[x].Selected == "1") {
                        option.defaultSelected = true;
                    }
                    select.appendChild(option);
                }

这在IE之外运行良好,为什么IE兼容模式不将其识别为选定选项?

您应该设置option元素的selected属性:

if (m_documents_Merge.DocumentsAttachments[i].Previews[x].Selected == "1") {
    option.selected = true;
}

您可以使用选项构造函数创建选项:

for (var x = 0; x < docpreviews.length; x++) {
    // new Option([text[, value[, defaultSelected[, selected]]]])
    option = new Option(docpreviews[x].PrevName, docpreviews[x].PrevId);
    if (m_documents_Merge.DocumentsAttachments[i].Previews[x].Selected == "1") {
        // To make the option selected, but does not make it the default selected option
        option.selected = true;
        // To make the option the default selected, but does not make it selected
        option.setAttribute('selected', true);
    }
    select.appendChild(option);
}

selected属性设置为true将使该选项处于选中状态,但不会使其成为默认的选中选项,即,重置表单不会将该选项设置为选中状态。

设置选定属性会将该选项设置为默认选定选项,即,如果重置表单,则会选择该选项,但不会使其成为当前选定的选项。

如果要选择该选项并将其作为默认的选定选项,请同时设置属性和特性。

defaultSelected属性在某些浏览器中是只读的,不能设置,尽管有些浏览器允许这样做。