通过脚本(.value)更改输入的事件

时间:2016-11-03 20:26:19

标签: javascript

是否存在触发每次更改的事件(用户和脚本)。我从2009年发现了一个堆栈问题,建议使用DOM Mutation。

人类是否为此发明了更好的解决方案?

P.S。有些人的代码,无法想象这种情况。

input = document.getElementById('input');
output = document.getElementById('output');
submit = document.getElementById('submit');

input.addEventListener('input', function(){
	output.innerText = "It works!";
})

submit.onclick = function(){
	input.value = 'Hello!';
}

//Firstly try to Submit. Oh look! Nothing happened!
//Now try to write anything. Hmm, it works!
<input id="input">
<button id="submit">Submit</button>
<div id="output"></div>

1 个答案:

答案 0 :(得分:0)

人类正在放弃突变事件

您可以通过MutationObserver类观察DOM中的各种更改。

为方便起见,直接从MDN(https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver):

&#13;
&#13;
// select the target node
var target = document.getElementById('SOME-ELEMENT-ID');
 
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});
 
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
 
// pass in the target node, as well as the observer options
observer.observe(target, config);
 
// later, you can stop observing
observer.disconnect();
&#13;
&#13;
&#13;