首页 > 解决方案 > Why does Edge mask the onchange event handler when an input has an input event handler that changes the input's value?

问题描述

In this HTML

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title></title>

    </head>

  <body>

    Enter some number here:
    <input  type="number" min="0" 
          oninput="console.log(' on input '); 
          this.value = Math.abs(this.value);"
          onchange="console.log(' on change');"/>

  </body>
</html>

The input has 2 event handlers

However onchange is not called.

Note, the oninput handler changes the value of the input. If I remove

this.value = Math.abs(this.value);

both events are fired.

This behaviour seen in Microsoft Edge 44.17763.1.0 (Microsoft EdgeHTML 18.17763)

This does not happen in Chrome nor in Firefox.

Questions

  1. What am I doing wrong?
  2. Is this from an inherited large code base with many input's all with an oninput and an onchange. The onchange is not called. What is the most efficient way to fix this? (Disclaimer:I'm no HTML / javascript expert.)

标签: javascripthtmlmicrosoft-edge

解决方案


oninput事件类似于onchange事件。不同之处在于,oninput 事件在元素的值发生更改后立即发生,而 onchange 事件发生在元素失去焦点时,在内容发生更改后。

我尝试使用 MS Edge、Chrome 和 Firefox 浏览器测试您的示例代码,并且能够使用 MS Edge 浏览器产生问题。

看起来 MS Edge 浏览器的工作方式略有不同。

我注意到如果你尝试在 head 部分编写 JS 代码,它可以帮助解决这个问题。

例子:

<!DOCTYPE html>
<html>
<body>
<input  type="number"   onchange="myFunction1(this.value)" oninput="myFunction(this.value)" />
<p id="demo"></p>
<p id="demo1"></p>

<script>
function myFunction(val) {
  document.getElementById("demo").innerHTML = "oninput " + val; 

}
function myFunction1(val) {
  document.getElementById("demo1").innerHTML = "onchange " + val; 
}
</script>

</body>
</html>

MS Edge 浏览器中的输出:

在此处输入图像描述

用户需要在更改值后按 ENTER 键或单击其他位置以触发事件。


推荐阅读