当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?
我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!
当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?
我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!
当前回答
非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'))
该元素现在可以由用户编辑,直到失去焦点。
其他回答
这里有一个更有效的版本,它对所有可内容使用on。这是基于上面的答案。
$('body').on('focus', '[contenteditable]', function() {
const $this = $(this);
$this.data('before', $this.html());
}).on('blur keyup paste input', '[contenteditable]', function() {
const $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
});
项目在这里:https://github.com/balupton/html5edit
下面是我最终使用的解决方案,效果非常好。我使用$(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();
如果您愿意,还可以删除/添加事件
以下是对我有效的方法:
var clicked = {}
$("[contenteditable='true']").each(function(){
var id = $(this).attr("id");
$(this).bind('focus', function() {
// store the original value of element first time it gets focus
if(!(id in clicked)){
clicked[id] = $(this).html()
}
});
});
// then once the user clicks on save
$("#save").click(function(){
for(var id in clicked){
var original = clicked[id];
var current = $("#"+id).html();
// check if value changed
if(original != current) save(id,current);
}
});
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
}
});