简体   繁体   English

InnerHTML 更改功能 JAVASCRIPT/JQUERY

[英]InnerHTML changed function JAVASCRIPT/JQUERY

i have 'ul li', where is text, i want that when text in 'li' changes after click happen something, for example console.log.我有“ul li”,文本在哪里,我希望当“li”中的文本在单击发生某些事情后发生变化时,例如console.log。 here is my code example:这是我的代码示例:

html: html:

<ul>
<li>first</li>
</ul>

<button>click</button>

javascript: javascript:

document.queryselector('button').addEventListener('click', function(){
let list = document.queryselector('li');
let text = list.innerHTML = 'second';
if(list.changed){
  console.log(changed);
}
});

One way to do this is with a MutationObserver.一种方法是使用 MutationObserver。

 document.querySelector('button').addEventListener('click', function(){ let list = document.querySelector('li'); let text = list.innerHTML = 'second'; }); const observer = new MutationObserver(function(mutationsList, observer) { for(let mutation of mutationsList) { // This will handle changes to the innerHTML, though the check isn't // really necessary since this is the only change we're observing if (mutation.type === 'childList') { console.log(mutation.target); } } }); observer.observe(document.getElementById("testNode"), { attributes: false, childList: true, subtree: false });
 <ul> <li id="testNode">first</li> </ul> <button>click</button>

MutationObserver reference MutationObserver 参考

This is a general way to watch for changes, but depending on the end goal of watching for the change there may be better ways to handle this situation.这是观察变化的一般方法,但根据观察变化的最终目标,可能有更好的方法来处理这种情况。 For example, if you know that the only way you'll end up changing the element is through clicking the button, I'd recommend that you route all of your handling through the same place.例如,如果您知道最终更改元素的唯一方法是单击按钮,我建议您将所有处理路由到同一位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM