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

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


当前回答

您需要使用输入事件类型

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

知道更多

其他回答

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/

非JQuery回答…

function makeEditable(elem){
    elem.setAttribute('contenteditable', 'true');
    elem.addEventListener('blur', function (evt) {
        elem.removeAttribute('contenteditable');
        elem.removeEventListener('blur', evt.target);
    });
    elem.focus();
}

要使用它,调用(比如说)一个id="myHeader"的头元素

makeEditable(document.getElementById('myHeader'))

该元素现在可以由用户编辑,直到失去焦点。

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

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