Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 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 Answer

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());
       }
    );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...