How to detect content change event on a div

前端 未结 3 1340
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 07:52

I am trying to make an editor everything working fine till now, but now I need to make a handler which could detect any change made in a div or any content edited in the div

相关标签:
3条回答
  • 2020-12-15 08:32

    Do you like this? http://jsfiddle.net/Ralt/hyPQC/

    document.getElementById( 't' ).onkeypress = function( e ) {
        var evt = e || window.event
        alert( String.fromCharCode( evt.which ) )
    }​
    

    It's not waiting for a change event, it's kind of pointless.

    Instead, it's listening to the onkeypress event. Everytime a user changes the content of this div (by adding a character to it), it triggers the event.

    You can also see how to get the character clicked (using String.fromCharCode( evt.which )).

    PS: a full jQuery solution for your specific case would be this:

    $( '#product_descriptioncontent' ).on( 'keypress', function() {
        $( '#your-hidden-input' ).val( $( this ).text() )
        // Or
        $( '#your-hidden-div' ).text( $( this ).text() )
    } )
    
    0 讨论(0)
  • 2020-12-15 08:40

    Try adding a handler for DOMCharacterDataModified. Might be a cleaner solution.

    0 讨论(0)
  • 2020-12-15 08:46

    You can bind a custom event to the div and trigger that event upon change

    Demo in Stack Snippets and jsFiddle:

    $(function() {
    
      $('#wrapper').bind("contentchange", function() {
        console.log("Captured content change event"); 
      });
    
      $("#btn").click(function() {
        $('#wrapper').html("new value").trigger("contentchange");
      });
      
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    
    <div id="wrapper"></div>
    <input type="button" id="btn" value="click here">

    0 讨论(0)
提交回复
热议问题