joh*_*sly 42 jquery contenteditable
更改div值时,如何触发事件?
<div class="changeable" contenteditable="true"> Click this div to edit it <div>
因此,当内容发生变化时,我想创建一个警报和/或做其他事情:
$('.changeable').text().change(function() {
  alert('Handler for .change() called.');
});
Nik*_*las 45
只需将内容存储到变量中,并在blur()事件发生后检查它是否不同.如果不同,请存储新内容.
var contents = $('.changeable').html();
$('.changeable').blur(function() {
    if (contents!=$(this).html()){
        alert('Handler for .change() called.');
        contents = $(this).html();
    }
});
示例:http://jsfiddle.net/niklasvh/a4QNB/
Bru*_*eur 17
你可以简单地使用jQuery的data()函数的focus/blur事件:
// Find all editable content.
$('[contenteditable=true]')
    // When you click on item, record into data("initialText") content of this item.
    .focus(function() {
        $(this).data("initialText", $(this).html());
    });
    // When you leave an item...
    .blur(function() {
        // ...if content is different...
        if ($(this).data("initialText") !== $(this).html()) {
            // ... do something.
            console.log('New data when content change.');
            console.log($(this).html());
        }
    });
});
更新:使用Vanilla JS
// Find all editable content.
var contents = document.querySelectorAll("[contenteditable=true]");
[].forEach.call(contents, function (content) {
    // When you click on item, record into `data-initial-text` content of this item.
    content.addEventListener("focus", function () {
        content.setAttribute("data-initial-text", content.innerHTML);
    });
    // When you leave an item...
    content.addEventListener("blur", function () {
        // ...if content is different...
        if (content.getAttribute("data-initial-text") !== content.innerHTML) {
            // ... do something.
            console.log("New data when content change.");
            console.log(content.innerHTML);
        }
    });
});
Blo*_*sie 12
我构建了一个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();
如果您愿意,也可以删除/添加活动
小智 11
目前最好的解决方案是HTML5输入事件
<div contenteditable="true" id="content"></div>
在你的jquery.
$('#content').on('input', (e) => {
    // your code here
    alert('changed')
});
小智 7
使用EventListener(不是jQuery方法)来做它更简单:
document.getElementById("editor").addEventListener("input", function() {
   alert("input event fired");
}, false);
        小智 6
这是我的方法......
$('.changeable').focusout(function() {
  alert('Handler for .change() called.');
});