contenteditable change events

前端 未结 19 2679
粉色の甜心
粉色の甜心 2020-11-22 01:36

I want to run a function when a user edits the content of a div with contenteditable attribute. What\'s the equivalent of an onchange

19条回答
  •  猫巷女王i
    2020-11-22 01:45

    Here's what worked for me:

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

提交回复
热议问题