我使用onchange但是代码被激活onblur加上代码在IE中不起作用

时间:2011-12-23 12:35:44

标签: javascript html javascript-events

的问题:

  1. 在Chrome和Firefox中代码有效,但事件被触发onblur我输入 [通过使用onkeyup而不是onchange解决]
  2. 这根本不适用于IE! [通过使用Option对象解决,请参阅更新..]
  3. HTML:

    <input type="text" onchange="getLocations(this)" />
    <select size="6" multiple="multiple" id="locationOpt"></select>
    

    JavaScript的:

    function getLocations(element) {
        var locations = Array("red","green","blue");
        var location_matched = [];
    
        for ( i in locations ){
                if(locations[i].search(element.value) > -1){
                        location_matched.push(locations[i]);    
                }
        }
    
        var html = "";
        for( i in location_matched){
                html += "<option value =\"" + i + "\">" + location_matched[i] + "</option>"; 
        }
        document.getElementById("locationOpt").innerHTML = html;
    }
    

    更新

    这是最终的工作代码:
    HTML:

    <input type="text" onkeyup="getLocations(this)" />
    <select size="6" multiple="multiple" id="locationOpt"></select>
    

    JavaScript的:

    function getLocations(element) {
        var locations = Array("red","green","blue");
        var location_matched = [];
    
        for ( i in locations ){
                if(locations[i].search(element.value) > -1){
                        location_matched.push(locations[i]);    
                }
        }
    
    var optionList = document.getElementById("locationOpt");
    
        //to remove all options
    while (optionList.options.length) {
                optionList.remove (0);
        }
    
    for( i in location_matched){
        // Option (text, value)
                var locationOption = new Option (location_matched[i], i);
                optionList.options.add (locationOption);
    }
    }
    

2 个答案:

答案 0 :(得分:1)

要在用户输入时检测更改,您必须使用onkeypress事件。这里已经回答了类似的问题:Detecting "value" of input text field after a keydown event in the text field?

答案 1 :(得分:1)

对IE使用onpropertychange(这也会在剪切/粘贴时触发) 此外:您应该使用new Option()来创建和插入选项,而不是操作innerHTML。