[英]Add Options to select drop down in IE
我正在尝试在运行时将项目添加到选择下拉列表中。 到目前为止,它可以在Firefox和Opera中运行,但似乎不能在IE7或8中运行。
应该发生的是,当用户选择一个中心时,人员下拉列表中就会出现该中心的人员。
//Clear out the all of the exisiting items
if (document.getElementById("ddlPersonnel").hasChildNodes) {
while (document.getElementById("ddlPersonnel").childNodes.length > 0) {
document.getElementById("ddlPersonnel").removeChild(document.getElementById("ddlPersonnel").firstChild);
}
}
//Add the "Select Personnel" option
var FirstOpt = document.createElement('OPTION');
FirstOpt.value = "";
FirstOpt.innerText = "Select Personnel";
alert("blah1");
document.getElementById("ddlPersonnel").options.add(FirstOpt, null); //It dies here with a "Type Mismatch" error
alert("blah2");
它死于两个警报之间的行,并显示“类型不匹配”错误。
使用新的Option而不是createElement。
var sel = document.getElementById("ddlPersonnel");
var opt = sel.options;
opt[opt.length] = new Option("Label","Value")
(那应该可以,但是我还没有测试过)
只需更换
document.getElementById("ddlPersonnel").options.add(FirstOpt, null);
通过
document.getElementById("ddlPersonnel").add(FirstOpt);
在add()函数中删除“ .options”和“,null”可以解决问题
以我的经验,用纯JavaScript appendChild()
方法替换jQuery的append()
导致我的项目出现在选择框中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.