2016-11-03 48 views
-3

是否存在触发每个更改(包括用户和脚本)的事件。我从2009年发现了一个堆栈问题,其中有人建议使用DOM突变。通过脚本输入更改的事件(.value)

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

P.S.一些代码为人们,谁也无法想象的情况。

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

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

 
submit.onclick = function(){ 
 
\t 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>

+0

你指的是什么样的_change_的? – tmslnz

+0

不,我不认为在Javascript中更改输入的值时会触发任何事件。您需要更改执行更改的代码来调用您的函数。 – Barmar

+0

@tmslnz这是代码。 – MaxelRus

回答

0

人类是在下降突变事件

你可以观察,适用于各种通过MutationObserver类的DOM变化的过程。

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

// 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();