以下js在FF2中工作正常,但在IE6中,下拉列表总是选择一个早期选项,IE - > testix2 vs. FF2 - > testix3 如果我们在脚本中的某处添加一个alertBox,它在IE6中也能正常工作。 但是如何在没有alertBox的情况下解决这个问题?
TIA
<script language="JavaScript" type="text/javascript">
<!--
function Entry(value, name, selected) {
this.value = value;
this.name = name;
this.selected = selected;
}
//-->
</script>
<select id="selSeaShells">
</select>
<script language="JavaScript" type="text/javascript">
<!--
var productCategoryLevel2 = new Array();
productCategoryLevel2.push(new Entry('Hallo1', 'testix1', false));
productCategoryLevel2.push(new Entry('Hallo2', 'testix2', false));
productCategoryLevel2.push(new Entry('Hallo3', 'testix3', true));
var i = 0;
for (i in productCategoryLevel2) {
var optL2 = document.createElement('option');
optL2.selected = true;
optL2.text = productCategoryLevel2[i].name;
optL2.value = productCategoryLevel2[i].value;
if (productCategoryLevel2[i].selected == true) {
productCategoryLevel2[i].selected = true;
optL2.selected = true;
} else {
optL2.selected = false;
}
try {
document.getElementById("selSeaShells").add(optL2, null);
} catch(ex3) {
document.getElementById("selSeaShells").add(optL2);
}
}
//-->
</script>
答案 0 :(得分:3)
我不完全确定为什么你的例子不起作用,但如果你这样做就行了(即在&lt; select&gt;上设置selectedIndex而不是设置&lt; option&gt;选择的属性)。经过测试的FF3,IE6,Chrome。
var i = 0;
for (i in productCategoryLevel2) {
var optL2 = document.createElement('option');
optL2.text = productCategoryLevel2[i].name;
optL2.value = productCategoryLevel2[i].value;
try {
document.getElementById("selSeaShells").add(optL2, null);
} catch(ex3) {
document.getElementById("selSeaShells").add(optL2);
}
if (productCategoryLevel2[i].selected == true) {
document.getElementById("selSeaShells").selectedIndex = i;
}
}
答案 1 :(得分:0)
我现在无法对此进行测试,但您可能希望使用标准for(;;)循环而不是for..in构造迭代数组,而for..in构造只能在javascript中的对象上使用。
答案 2 :(得分:0)
这感觉就像一个IE错误(我想知道将true转换为1是一个问题),但是你已经通过选择索引基于选项而不是选择本身进行了修改。
重要的是要意识到,如果你从零选项开始,那么你想给第一个选项选择一个值并不重要 - 作为一个元素之一,它只能被选择=真。< / p>
(我同意三联关于for
)