javascript - 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
- input
- change
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
- What am I doing wrong?
- 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.)
解决方案
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 键或单击其他位置以触发事件。
推荐阅读
- angular - 如何以角度验证特定的ngModel
- snowflake-cloud-data-platform - Where are snowflake tables stored?
- python - 在python中的某个变量中从curl命令中获取数据
- concourse - 如何在 Concourse 任务运行配置中组合一个终端命令
- javascript - 如何安装 node_modules?
- javascript - 如何使用 Typescript 实现 Material-UI ThemeProvider 和 WithStyles
- java - 无法从 mysql 检索用户身份(用户名和密码)以登录
- ios - 如何使collectionView布局iOS 13无效
- sorting - 基于两种逻辑对数据进行分组
- wpf - 窗口 10 上的 WPF Listview 触摸问题:“触发了另一个数据模板的事件,而它可能不会发生”