【问题标题】:I used onchange but the code is fired onblur plus the code is not working in IE我使用了 onchange 但代码被触发 onblur 加上代码在 IE 中不起作用
【发布时间】:2011-12-23 12:35:43
【问题描述】:

问题:

  1. 在 Chrome 和 Firefox 中,代码有效,但事件被触发 onblur,我在键入 时需要它[通过使用 onkeyup 而不是 onchange 解决]
  2. 这在 IE 中根本不起作用! [通过使用 Option 对象解决,查看更新..]

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);
}
}

【问题讨论】:

  • 对于文本input 元素,change 事件仅在框失去焦点并且值更改时触发。如果你想在用户输入时实时更新,你必须监听一个或多个关键事件。
  • onkeyup 在我看来更好
  • 谢谢 Lucky,它可以在除 IE 之外的所有浏览器中使用?!

标签: javascript html javascript-events


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • onkeyup 是解决方案。感谢您的链接,但为什么这在 IE 中不起作用??????
    • 您使用的是哪个版本的 IE?您是否收到任何 JavaScript 错误消息?
    猜你喜欢
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2013-12-15
    • 1970-01-01
    相关资源
    最近更新 更多