如何检测div上的内容更改事件 [英] How to detect content change event on a div

查看:102
本文介绍了如何检测div上的内容更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使编辑器的一切工作正常,直到现在,但现在我需要制作一个处理程序,可以检测到div或div中编辑的任何内容的更改。

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

<?php $row="testing content" ?>
<!-- my editor section-->
<div id="editor">
    <div id="options">
        <span><a id="iimg">Insert Image from gallery</a></span>
        <span>Upload image to gallery</span>
        <span><a id="iheading">Heading</a></span>
    </div>
    <div id="product_descriptioncontent" contenteditable="true"><?php echo $row; ?>
    </div><!-- viewable editor -->
    <input type="hidden" name="textareacontent" value="" id="textareacontent" >
    <!-- hidden field to submit values -->
</div>
<!-- end of editor section -->
<div id="imc"></div> <!-- image gallery loading section -->

<script>
$(document).ready(function(){

    $('#iheading').click(function(){
    $('#product_descriptioncontent').append('<h1>Heading</h1>');
    });

    $('#iimg').click(function(){
        $('#imc').load('imagegallery.php',function(){
        $('#gallery img').on('click',function(){
            $('#product_descriptioncontent').append('<img  src="http://localhost/sites/site_pics/otherpic/1.png"><br>&nbsp;');
    });
    });
    });
    $('#product_descriptioncontent').change(function(){
    alert("pppp");// how to capture this event
    });
});
</script>

我已经把一些我的代码放在了jsfiddle http://jsfiddle.net/bipin000/UJvxM/1/
感谢您宝贵的时间

I have placed a bit of my code at jsfiddle http://jsfiddle.net/bipin000/UJvxM/1/ thanks for your precious time

推荐答案

你喜欢吗? 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.

相反,它正在听 onkeypress 事件。每次用户更改此div的内容(通过添加一个字符),它会触发该事件。

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.

您还可以看到如何获取点击的角色(使用 String.fromCharCode(evt.which))。

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

PS:一个完整​​的jQuery解决方案针对您的具体案例将是这个:

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

这篇关于如何检测div上的内容更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆