Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

javascript - jQuery: Watching for nodevalue change

I want to watch for the nodeValue change of an element that's edited with contenteditable. Basically, I want to run a function on change of the nodevalue.

I found this post: http://james.padolsey.com/javascript/monitoring-dom-properties/

Which seems to have a plugin for what I want.

Here's the watch plugin:

jQuery.fn.watch = function( id, fn ) {

    return this.each(function(){

        var self = this;

        var oldVal = self[id];
        $(self).data(
            'watch_timer',
            setInterval(function(){
                if (self[id] !== oldVal) {
                    fn.call(self, id, oldVal, self[id]);
                    oldVal = self[id];
                }
            }, 100)
        );

    });

    return self;
};

As an example, I can watch an input's value like this:

  $('#input').watch('value', function(propName, oldVal, newVal){
    $("#text").text(newVal);
  });

But not a contenteditable's nodevalue (its text content):

  $('#ce').watch('nodeValue', function(propName, oldVal, newVal){
    $("#text").text(newVal);
  });

Here's the live example:

http://jsbin.com/iconi/edit

Anyone know how to adapt the watch method to work with nodevalue. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Isn't this simpler?

 $('#ce')
    .bind('change keyup',
       function() {
          $('#text')
             .text($(this).text());
       }
    );

As for the input:

 $('#input')
    .bind('change keyup',
       function() {
          $('#text')
             .text($(this).val());
       }
    );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...