Javascript 由document.createElement(“OPTION”)创建的OPTION元素始终将所选属性设置为true

Javascript 由document.createElement(“OPTION”)创建的OPTION元素始终将所选属性设置为true,javascript,html,createelement,Javascript,Html,Createelement,我正在使用javascript和IE11实现下面的代码,通过使用javascript在组合框中添加选项 var bSelected = false; for (count of elements to be created) { **// set value and text and whether to selected the element or not** // Create an option and add it t

我正在使用javascript和IE11实现下面的代码,通过使用javascript在组合框中添加选项

    var bSelected = false;

    for (count of elements to be created)
    {
          **// set value and text and whether to selected the element or not**

          // Create an option and add it to the combo
          opt = document.createElement ("option");
          opt_txt = document.createTextNode (textPart);
          opt.appendChild (opt_txt);
          opt.setAttribute ("value", valuePart);
          opt.setAttribute ("text", textPart);
          opt.setAttribute ("selected", bSelected);
    }
现在,即使selected设置为false,opt.selected属性也始终显示为true。createElement函数创建元素后,默认值为true。请说明为什么它没有变为false


在IE9中,它可以正常工作(不同的HTML版本?

选中的
属性唯一允许的值是
“selected”
(或
“selected”
,意思相同),但浏览器中的错误恢复意味着任何值都将被视为是
“selected”

当您调用
opt.setAttribute(“selected”,bSelected)时
,则将
bSelected
的值转换为字符串并设置为该值

在这种情况下,
false
被转换为
“false”
,并被视为
“selected”

在处理布尔属性时,如果您不希望设置它们,则根本不设置它们


或者,可以设置选定的DOM属性而不是属性。该属性确实采用
true
false
,而不是
“选定”


您是否尝试过完全不设置为“选定”状态?请等待,直到您完全填充“选择”元素(使用所有选项),然后在所需的元素上设置“选定”。单独设置它是一种浪费(但它应该可以工作)。下拉列表框总是将选项显示为选中状态,因此,如果您刚刚创建了它,则会选中第一项。@trincot在我的例子中,所有选项都是选中状态:(只需删除
opt.setAttribute(“选中”,bSelected);
。在其中选择
就是选择元素,无论是真是假。
opt.selected = bSelected;