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

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


当前回答

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

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

创建一个快速的jQuery contentteditable插件

其他回答

下面是我最终使用的解决方案,效果非常好。我使用$(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!');
    }
});

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/

您需要使用输入事件类型

Demo

HTML

<div id="editor" contenteditable="true" >Some text here</div>

JS

const input = document.getElementById('editor');


input.addEventListener('input', updateValue);

function updateValue(e) {
  console.log(e.target);
}

知道更多

我构建了一个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();

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

看看这个想法。 http://pastie.org/1096892

我觉得很接近了。HTML 5确实需要将更改事件添加到规范中。唯一的问题是回调函数在$(this). HTML()中内容实际更新之前计算if (before == $(this). HTML())。setTimeout不起作用,这很可悲。让我知道你的想法。