开发者

Why doesn't this onchange event work?

if (!localStorage.text) localStorage.text = document.body.innerHTML;

function ifChanged() {
    document.body.innerHTML.onchange = function() {
        if (document.body.innerHTML !== (localStorage.text)) alert("No match");
    };
}

ifChanged();

It doesn't check if it chan开发者_Go百科ged. What went wrong?


It's not working because the onchange event is for form fields (it fires when the field's value changes). It is not fired when the HTML changes, just, for example, when a user types a key in a textbox.

The best way to know when something on the page changes is to have the code that is making the changes in the first place signal that a change is being made (this could be cleanly done with some sort of event broadcast).

If you really want to do it this way, you could use a timer that periodically polls for changes:

setInterval(ifChanged, 1000);    // Check once every second (1000ms)


document.body.innerHTML returns a string and String.onChange and String.setEventListener('change', ...); are undefined. The DOM 2 introduce MutationEvents which will fire when the DOM is changed. Unfortunately, those events are not widely implemented and may slow down every change in the DOM.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜