当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?

我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!


当前回答

这个帖子在我调查这个主题的时候非常有帮助。

我把这里的一些代码修改成一个jQuery插件,这样它就可以以一种可重用的形式使用,主要是为了满足我的需求,但其他人可能更喜欢一个简单的界面来使用可满足的标记。

https://gist.github.com/3410122

更新:

由于其日益流行的插件已被Makesites.org采用

发展将从这里开始:

https://github.com/makesites/jquery-contenteditable

其他回答

下面是我最终使用的解决方案,效果非常好。我使用$(this).text()代替,因为我只是使用了内容可编辑的一行div。但是你也可以使用.html(),这样你就不必担心全局/非全局变量的作用域,而before实际上是附加到编辑器div的。

$('body').delegate('#editor', 'focus', function(){
    $(this).data('before', $(this).html());
});
$('#client_tasks').delegate('.task_text', 'blur', function(){
    if($(this).data('before') != $(this).html()){
        /* do your stuff here - like ajax save */
        alert('I promise, I have changed!');
    }
});

我构建了一个jQuery插件来做到这一点。

(function ($) {
    $.fn.wysiwygEvt = function () {
        return this.each(function () {
            var $this = $(this);
            var htmlold = $this.html();
            $this.bind('blur keyup paste copy cut mouseup', function () {
                var htmlnew = $this.html();
                if (htmlold !== htmlnew) {
                    $this.trigger('change')
                }
            })
        })
    }
})(jQuery);

你可以简单地调用$('.wysiwyg').wysiwygEvt();

如果您愿意,还可以删除/添加事件

为了避免计时器和“保存”按钮,你可以使用blur事件,当元素失去焦点时触发。但是为了确保元素确实被改变了(不仅仅是聚焦和散焦),它的内容应该与它的上一个版本进行比较。或者使用keydown事件在这个元素上设置一些“脏”标志。

onchange事件不会在具有contentEditable属性的元素被更改时触发,建议的方法是添加一个按钮,以“保存”版本。

检查这个插件,它以这种方式处理问题:

创建一个快速的jQuery contentteditable插件

2022年更新

正如评论中所指出的,这并没有回答所提出的问题,即需要更改事件而不是输入事件的等价物。不过,我还是把它留在这里吧。

原来的答案

I'd suggest attaching listeners to key events fired by the editable element, though you need to be aware that keydown and keypress events are fired before the content itself is changed. This won't cover every possible means of changing the content: the user can also use cut, copy and paste from the Edit or context browser menus, so you may want to handle the cut copy and paste events too. Also, the user can drop text or other content, so there are more events there (mouseup, for example). You may want to poll the element's contents as a fallback.

2014年10月29日更新

从长远来看,HTML5输入事件是答案。在撰写本文时,当前的Mozilla(来自Firefox 14)和WebKit/Blink浏览器支持可满足的元素,但不支持IE。

演示:

. getelementbyid(“编辑器”)。addEventListener("input", function() { Console.log("触发的输入事件"); },假); <div contentteditable ="true" id="editor">请在这里输入一些内容</div>

演示:http://jsfiddle.net/ch6yn/2691/