【问题标题】:Why this javascript event isn't working on IE ..?为什么这个 javascript 事件在 IE 上不起作用 ..?
【发布时间】:2010-02-08 13:27:41
【问题描述】:

我正在尝试根据在其他下拉列表中所做的选择将选项加载到下拉列表。我编写的代码几乎可以在所有主流浏览器、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 来模拟它。请帮我调试代码。

【问题讨论】:

  • 快速浏览一下,我看不出脚本有什么问题。可能是您期望立即触发 onchange 事件,而实际上它仅在控件失去焦点时触发(您单击/选择下拉框以外的任何内容)。跨度>
  • @miguel,对不起,我没明白你的意思。
  • @miguel,我的要求正如我所提到的,需要根据另一个选择元素更改选项值。

标签: javascript html events drop-down-menu


【解决方案1】:

是的,许多“特殊”元素(例如 &lt;select&gt;&lt;table&gt;)不能在 IE 中设置它们的 innerHTML

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

通常最好使用 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);
}

【讨论】:

    【解决方案2】:

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

    或者,您可以使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      相关资源
      最近更新 更多