<html>
<body onload="init()">
<div id="test"><div>
<script>
function init() {
aSelect = document.createElement("select");
aSelect.name = 'test';for(var i = 1; i <=5; i++) {
aOption = document.createElement("option");
aOption.value = i;
aOption.text = i;
if(i == 3) {
aOption.selected = true;
}
aSelect.options.add(aOption);
}
document.getElementById("test").appendChild(aSelect);
}
</script>
</body>
</html>
在IE中默认选择2,在FF中默认选择3,程序的本意是要选择3
请大家帮忙看看出什么问题了?
if(isie)aSelect.value=2;
else if(isff)aSelect.value=3;
if(i == 3) {
aOption.selected = true;
}这里已经指定了 3这个选项是默认选择的
我不是要在IE中选择2,在FF中选择3,而是,上面那段代码实际的显示(IE中为2,FF中为3)两个浏览器的表现不一样.
if(isie)str[2].selected=true;
else if(isff)str[3].selected=true;
<body onload="init()">
<div id="test"><div>
<script>
function init() {
aSelect = document.createElement("select");
aSelect.name = 'test';
aSelect.options.length=0;for(var i = 1; i <=5; i++) {
var aOption = document.createElement("option");
aSelect.options.add(aOption);
aOption.value = i;
aOption.text = i;
if(i == 3) {
aOption.selected = true;
}
}
document.getElementById("test").appendChild(aSelect);
}
</script>
</body>
</html>
IE中你要先加到DOM TREE才能选中;
我无论想要哪个被选中,其实际的效果都是他的上一个选项被选中(IE中),在FF中一直正常
把 aSelect.options.add(aOption); 提前就好了.
如果说他彻底不能设置的话那么他应该一直是第一个才对啊
alert(aSelect.innerHTML)
会看到
firefox并不是立刻把selected属性加上去标签的.
FF确实不是,但是IE立刻就给2加了selected属性