如果 div innerText 更改,则触发 JavaScript 事件

5 javascript addeventlistener innertext

我想在 div 的 innerText 更改时发出警报:

myDiv.addEventListener("change", function() {
    if (myDiv.innerText != "some text")
        alert('innerText has changed.');
},false);
Run Code Online (Sandbox Code Playgroud)

没有用,请帮忙。

Vis*_*ary 12

myDiv.addEventListener("DOMCharacterDataModified", function (event) { // ... add your code he }, false);

使用 DOMCharacterDataModified 检测 innerText 更改事件


hal*_*fer 6

代表 OP 发布

我找到了一个解决方案:

// THIRD FUNCTION (changes the text)
var i = 0;
function thirdFUN(){
    i++;
    var popo = document.getElementById('myDiv');
    popo.innerText = i;
}
setInterval(thirdFUN, 500);

//---------------------------------------------------------------

// JQUERY
/*var popo = $('#myDiv');
$('#myDiv').bind("DOMSubtreeModified",function(){
    if (popo.html() == "10")
    console.log('changed');
});
*/

//---------------------------------------------------------------

// PURE JS
window.onload = function(){

var popo = document.querySelector('#myDiv');

var observer = new MutationObserver(function(mutations){
    mutations.forEach(function(mutation){
        console.log(mutation.type); // <- It always detects changes
        if (popo.innerHTML == "10"){
            alert('hello');
        }
    });    
});

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

}
Run Code Online (Sandbox Code Playgroud)

也是一个 JS Fiddle


小智 -3

尝试

document.addEventListener("change", function()......