为什么这个javascript事件不适用于IE ..?

时间:2010-02-08 13:27:42

标签: javascript html events drop-down-menu

我正在尝试将选项加载到下拉列表,具体取决于在其他下拉列表中所做的选择。我编写的代码几乎适用于所有主流浏览器,FF,Opera,Safari,但在IE7中不起作用。

这是我的Javascript代码:

<script type = "text/javascript">
var txt1 = "<option>state1<\/option><option>state2<\/option><option>state3<\/option><option>state4<\/option>";
var txt2 = "<option>stateA<\/option><option>stateB<\/option><option>stateC<\/option><option>stateD<\/option><option>stateE<\/option>";

function states_val() {

    if(document.getElementById("country").options[0].selected==true) {
        document.getElementById("states").disabled=true;
        document.getElementById("states").innerHTML="<option>Select country<\/option>";
    }
    else if(document.getElementById("country").options[1].selected==true) {
        document.getElementById("states").disabled=false;
        document.getElementById("states").innerHTML=txt1;
    }
    else if(document.getElementById("country").options[2].selected==true) {
        document.getElementById("states").disabled=false;
        document.getElementById("states").innerHTML=txt2;
    }
}
</script>

和HTML代码:

<select id="country" name="name_country" onchange="states_val()">
    <option>select</option>
    <option>country1</option>
    <option>country2</option>
</select>
<select id="states" name="name_states"></select>

我绑定了客户端脚本,只能使用Javascript进行模拟。请帮我调试代码。

2 个答案:

答案 0 :(得分:7)

是的,<select><table>等许多“特殊”元素都无法在IE中设置innerHTML

如果您想从字符串设置innerHTML,则必须以迂回方式进行设置:将innerHTML个临时div元素设置为<select> +您的选项+ </select>,然后将所有选项对象从新选择移动到旧选项。

通常最好使用DOM方法而不是innerHTML和转义标记:

function setOptions(select, options) {
    select.options.length= 0;
    for (var i= 0; i<options.length; i++)
        select.options[i]= new Option(options[i]);
}

var statemap= [
     ['Select country'],
     ['Karnataka', 'MP', 'UP', 'Jammu & Kashmir', 'Himachal Pradesh'],
     ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Delaware', 'Florida']
];
function states_val() {
    var states= statemap[document.getElementById('country').selectedIndex];
    setOptions(document.getElementById('states'), states);
}

答案 1 :(得分:2)

我认为这是一个确认的错误(http://alexle.net/archives/150)解决方案是替换整个select元素而不仅仅是innerHTML(选项..)

或者,您可以使用

手动创建选项节点
var anOption = document.createElement('option');
anOption.innerHTML = '..';
anOption.value = '..';
document.getElementByID('states').appendChild(anOption);