Cai*_*aio 16 javascript triggers onchange
仅当USER输入某个值时才会触发"onchange"事件.当我通过Javascript自动更改值时,为什么无法触发事件?还有其他选择吗?
动画:

码:
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener ("DOMContentLoaded", function () {
var input = this.getElementsByTagName ("input")[0];
var div = this.getElementsByTagName ("div")[0];
var i = 0;
var seconds = 5;
div.innerHTML = "The following input should fire the event in " + seconds + " seconds";
var interval = window.setInterval (function () {
i ++;
if (i === seconds) {
window.clearInterval (interval);
input.value = "Another example";
div.innerHTML = "Nothing ! Now try change the value manually";
}
else {
div.innerHTML = "The following input should fire the event in " + (seconds - i) + " seconds";
}
}, 1000);
input.addEventListener ("change", function () {
alert ("It works !");
}, false);
}, false);
</script>
<style>
body {
padding: 10px;
}
div {
font-weight: bold;
margin-bottom: 10px;
}
input {
border: 1px solid black;
border-radius: 3px;
padding: 3px;
}
</style>
<title>Event</title>
</head>
<body>
<div></div>
<input type = "text" value = "Example" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
谢谢
T.J*_*der 21
绝大多数情况下,您不希望在使用代码更改值时触发事件.在您这样做的情况下,您可以通过现代浏览器触发合成事件dispatchEvent.更多这里.
所以在你的具体例子中:
input.value = "Another example";
var event = document.createEvent("UIEvents"); // See update below
event.initUIEvent("change", true, true); // See update below
input.dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)
更新:正如本杰明所说,由于上面写的,initUIEvent已经被UIEvent 构造函数替换,所以这将是:
input.value = "Another example";
var event = new UIEvent("change", {
"view": window,
"bubbles": true,
"cancelable": true
});
input.dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)
或者,您可以随时直接调用您绑定到change事件的任何函数,这通常是我要做的.但有时您希望使用实际事件(例如,使用观察者模式时)并确保通知任何正在侦听更改的人.
请注意,initUIEvent已弃用并从 Web 标准中删除,如下所述:developer.mozilla.org/en-US/docs/Web/API/UIEvent/initUIEvent
除了不使用之外,这是相同的initUIEvent:
input.value = 'Another example';
var event = new UIEvent('change', {
'view': window,
'bubbles': true,
'cancelable': true
});
input.dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)