Internet Explorer 10“输入”事件在数据列表选项选择上未触发

时间:2018-10-25 21:02:57

标签: javascript internet-explorer-10 dom-events html-datalist

在下面的示例中,我有一个输入字段和随附的数据列表元素。我正在尝试编写JavaScript,当用户从列表中选择一个项目时,它会监听。我已经看到它建议为此使用“输入”事件,并且在Chrome,Firefox等中都可以使用。问题是Internet Explorer。

在IE10中,我得到以下行为:

  • 在字段中键入会触发事件。
  • 从数据列表中选择一个项目不会第一次触发该事件。
  • 重新选择相同的选项会触发该事件。

查看测试

enter image description here

$('input').on('input', function(){
    console.log($('input').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />

<datalist id="ice-cream-flavors">
    <option value="Chocolate">
    <option value="Coconut">
    <option value="Mint">
    <option value="Strawberry">
    <option value="Vanilla">
</datalist>

对于我如何强制Internet Explorer触发该(或任何)事件,以便用户进行选择时我可以运行功能,是否有人有任何建议?

1 个答案:

答案 0 :(得分:0)

我在IE11上遇到了同样的问题,它基于以下内容创建了自定义自动填充列表:https://www.w3schools.com/howto/howto_js_autocomplete.asp

一些测试表明,当远离输入框单击时(即失去焦点时),IE11触发了input事件。与其他浏览器一样,预期的行为是仅在输入字段中的文本输入(包括退格)时触发此事件。

解决方案是检查IE中的输入值是否已更改,如下所示:

function inputEventGeneral(input, fn) { //input event for any browser
    if (checkBrowserIE()) {
        inputEventIE(input, fn);
    } else {
        input.addEventListener('input', function (e) { //normal input event for Chrome, FF, etc.
            fn(this); //run this function on input
        });
    };
};

function inputEventIE(input, fn) { //input event for IE
    let curr = '';
    let prev = '';

    input.addEventListener('input', function (e) {
        curr = this.value;

        if (prev === curr) { //check if value changed
            return;
        };

        prev = curr; //update value of prev

        fn(this); //run this function only if the value has been changed
    });
};


function checkBrowserIE() {
    return (/Trident/.test(navigator.userAgent)); //https://stackoverflow.com/questions/22004381/ie-input-event-for-contenteditable
};

在IE中,文本输入字段上还存在'x'清除按钮的问题,当使用上述代码时,该按钮不会触发输入事件。为此,您可以a)只需使用CSS隐藏该清除按钮,如下所示:

input[type=text]::-ms-clear { display: none; }

或b)您可以修改上面的代码以将prev的值存储在data-prev属性或全局变量中,然后使用输入表单值的任何更改来更新它(例如,当从自动完成列表/数据列表中选择)。然后,这将导致在单击清除按钮时触发事件,因为清除时prev值( val )与curr值('')会有所不同。

希望有帮助!