javascript - 为什么这个 javascript 事件不能在 IE 上运行 ..?

标签 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 来模拟它。请帮我调试代码。

最佳答案

是的,许多“特殊”元素,例如 <select><table>不能有他们的 innerHTML在 IE 中设置。

如果你想设置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);
}

关于javascript - 为什么这个 javascript 事件不能在 IE 上运行 ..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2221838/

相关文章:

javascript - Raphael.js 点击事件

.net - Avalon 文本编辑器中上下键的光标位置没有改变

javascript - jQuery 鼠标点击计数器 - 如何重置?

html - 为什么宽度会改变?

javascript - 浏览器缩小会破坏页面布局

html - 根据类名包含隐藏DIV

javascript - 遍历 Javascript 中的对象键

javascript - 'declare' 在 JavaScript 中的作用是什么?

javascript - 从序列化函数中获取 HTML 的值

javascript - 被所有的 promise 迷惑