最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why doesn't this onchange event work? - Stack Overflow

programmeradmin0浏览0评论
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 changed. What went wrong?

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 changed. What went wrong?

Share Improve this question asked Jul 2, 2011 at 16:29 David GDavid G 97k41 gold badges172 silver badges258 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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)

  1. 暂无评论