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

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


当前回答

我修改了律法,希望罪恶的答案是这样的,这对我有用。我使用keyup事件而不是keypress,这工作得很好。

$('#editor').on('focus', function() {
  before = $(this).html();
}).on('blur keyup paste', function() { 
  if (before != $(this).html()) { $(this).trigger('change'); }
});

$('#editor').on('change', function() {alert('changed')});

其他回答

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

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

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

JQuery的一个简单的答案,我刚刚创建了这段代码,并认为它将对其他人也有帮助

    var cont;

    $("div [contenteditable=true]").focus(function() {
        cont=$(this).html();
    });

    $("div [contenteditable=true]").blur(function() {
        if ($(this).html()!=cont) {
           //Here you can write the code to run when the content change
        }           
    });

根据@balupton的回答:

美元(文档)。On ('focus', '[contenteditable]', e => { Const self = $(e.target) 自我。数据(‘前’,self.html ()) }) 美元(文档)。On ('blur', '[contenteditable]', e => { Const self = $(e.target) If (self.data('before') !== self.html()) { self.trigger(“变化”) } }) < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>

const p = document.querySelector('p') const result = document.querySelector('div') const观察者= new MutationObserver((mutationRecords) => { 结果。textContent = mutationRecords[0].target.data / /结果。textContent = p.textContent }) 观察者。观察(p, { characterData:没错, 子树:没错, }) abc contenteditable < p > < / p > < div / >