jQuery:观察nodevalue的变化 [英] jQuery: Watching for nodevalue change

查看:97
本文介绍了jQuery:观察nodevalue的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要观察使用contenteditable编辑的元素的nodeValue更改。基本上,我想在更改nodevalue时运行一个函数。

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.

我发现这篇文章:
http://james.padolsey.com/javascript/monitoring-dom-properties/

这似乎有我想要的插件。

Which seems to have a plugin for what I want.

这是手表插件:

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

但不是contenteditable的nodevalue(其文本内容):

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

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

以下是实例:

< a href =http://jsbin.com/iconi/edit =nofollow noreferrer> http://jsbin.com/iconi/edit

任何人都知道如何调整watch方法以使用nodevalue。谢谢!

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

推荐答案

这不是更简单吗?

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

至于输入:

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

这篇关于jQuery:观察nodevalue的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆