Javascript Eventlistener for Update / Change on Element / innerText

时光总嘲笑我的痴心妄想 提交于 2019-12-07 08:27:13

问题


Is there a eventListener who is just checking the changes of an innerText?

Example:

12345

I just want to check if "12345" is changing to something else like "23415".

There is no "click" event that will comes up or anything else. I don't have the chance to go through the code where the updates from the span's are coming. So I really can just only grab the event from the changes in the span element but I don't have any clue how.

Sorry for my bad English and thanks!


回答1:


Check out the MutationObserver. Using it you can listen to changes of the observed element's characterData. Example:

HTML

<span class="observable" contenteditable="true">12345</span>

JS

var observables = document.querySelector('.observable');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation);
  });    
});

var config = {characterData: true, subtree: true};
observer.observe(observables, config);

FIDDLE

Note that subtree has to be true because the text actually is a child element of the observed element.




回答2:


The accepted answer might not work on all browsers if the text being updated via the innerHTML property. In this case, Firefox (as of 28) treats this as a childList event type, while Chrome (as of 33) treats this as a characterData event type. My guess is Chrome checks if the child node being update is a text node.

Firefox will fire characterData mutation events if the text is updated via user input (like via contenteditable as in the example).

In conclusion, if you want to watch for Javascript updating the innerHTML of an element, make sure to add childList:true to your MutationObserverInit object to be compatible with Firefox.




回答3:


Just in case anyone is looking for a way to do this for multiple nodes. fiddle Further reading

HTML

<span class="observable" contenteditable="true">13436</span>
<span class="observable" contenteditable="true">13235</span>

JS

var observables = document.querySelectorAll('.observable');
console.log(observables);
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation);
  });
});

var config = {
  characterData: true,
  subtree: true
};
observables.forEach(function(node) {
  observer.observe(node, config);
});


来源:https://stackoverflow.com/questions/20613754/javascript-eventlistener-for-update-change-on-element-innertext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!