How to detect content change event on a div

前端 未结 3 1345
佛祖请我去吃肉
佛祖请我去吃肉 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() )
    } )
    

提交回复
热议问题