2

是的,这在 FF 和 Chrome 中有效,但由于某种原因在 IE 8 中无效。我正在使用单选按钮来清除表单的一部分。该部分是一个选择框,但我不想离开区域为空 - 相反,我想将其重置为页面加载时的状态。目前 IE8 只给我留下了一个空的小选择框。

html:

<select id="city_select" disabled="true" name="location_id" onchange="show_search_button();"><option selected>Select your city</option> </select>

Javascript:

document.getElementById('city_select').innerHTML = "<option selected>Select your city</option>";

我也尝试在 javascript 中使用 location_id 而不是 city_select 但无济于事.. innerText 和 innerContent 也不起作用.. 虽然 inner.HTML 在 IE8 中适用于早期功能,但这并不是试图将 innerHTML 转换为表单。有谁知道为什么这适用于 Chrome 和 FF 而不是 IE8?有没有解决办法?任何帮助表示感谢!

4

2 回答 2

0

尝试这个:

document.getElementById('city_select').options.length = 0;

然后创建一个新选项并将其推送到选择的选项数组中。这些选项有点棘手,与其他标记不同。

编辑以显示如何创建选项:

var sel = document.getElementById('city_select').options.length = 0;
var opt = document.createElement('option');
opt.value = "Select Your City";
sel.options.push(opt);
sel.selectedIndex = 0;
于 2010-04-03T01:24:11.653 回答
0

应该有 4 种方式将新选项分配给选择元素。有些适用于某些场景,有些适用于其他场景。看这里 -如何在 IE Windows Mobile 5 中向 <SELECT> 添加选项

对我来说,Robusto 的解决方案没有奏效,原因有以下三个:

1)sel分配第一行中的变量,document.getElementById('city_select').options.length = 0;而不是简单地持有选择元素(供稍后在第 4 行和第 5 行使用),然后在下一行删除选项,如下所示:

var sel = document.getElementById('city_select');
sel.options.length = 0;

2)第 4 行sel.options.push(opt)(或稍后建议sel.options[0] = opt)抛出Object does not support this property or method错误。而是使用这个:

sel.appendChild(opt);

3)除了为选项分配值之外,您还必须分配要显示的文本。你这样做:

opt.innerText = "Select Your City - displayed";

因此,总结整篇文章:

var sel = document.getElementById('city_select');
sel.options.length = 0;
var opt = document.createElement('option');
opt.value = "Select Your City";
opt.innerText = "Select Your City - displayed";
sel.appendChild(opt);
sel.selectedIndex = 0;
于 2012-06-16T14:24:59.100 回答