在IE中使用. innerhtml添加选项元素

Adding option elements using .innerHTML in IE

本文关键字:添加 选项 元素 innerhtml IE      更新时间:2023-09-26

我有一个txt变量,它包含我的html字符串,我需要为下拉列表设置。该代码在除IE以外的所有其他浏览器中都可以正常工作。基本代码如下所示:

while循环加上更多代码

document.getElementById('theSelector').innerHTML = txt;

其中'theSelector'是我的select元素的id

所以IE会退出,不会生成列表。如果你想看看我的源代码和我所做的一切,我将把我的网页贴在下面。如果你想看看该网站应该如何运行,只需在另一个浏览器,而不是ie.

http://1wux.com/Resume/signUp.html

根据您的评论,它没有生成您的列表,以及Jared的评论,您正在尝试添加选项,尝试如下:

var list = document.getElementById('theSelector');
var newOp = document.createElement("option");
newOp.text = "Txt";
newOp.value = "1";
list.options.add(newOp);

编辑

根据Jared的评论,以下可能为您提供一些性能优势:

list.options[list.options.length] = newOp;

正如其他人提到的,这是所有版本的IE中的一个错误。我会使用@AdamRackis的解决方案,但如果你必须用字符串构建你的HTML,唯一的解决方法似乎是使用outerHTML并将<select>包含在字符串中。

演示:http://jsfiddle.net/ThinkingStiff/TWYUa/

HTML:

<select id="select"></select>

脚本:

var options = '<select id="select"><option>one</option><option>two</option></select>';
document.getElementById( 'select' ).outerHTML = options;

使用Jquery

$('#theSelector').html(txt);