jQuery: Watching for nodevalue change

馋奶兔 提交于 2019-11-28 09:57:55

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/1546348/jquery-watching-for-nodevalue-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!