jQuery Event : Detect changes to the html/text of a div

后端 未结 13 2619
旧巷少年郎
旧巷少年郎 2020-11-22 06:15

I have a div which has its content changing all the time , be it ajax requests, jquery functions, blur etc etc.

Is there a way

13条回答
  •  清歌不尽
    2020-11-22 07:02

    There is no inbuilt solution to this problem, this is a problem with your design and coding pattern.

    You can use publisher/subscriber pattern. For this you can use jQuery custom events or your own event mechanism.

    First,

    function changeHtml(selector, html) {
        var elem = $(selector);
        jQuery.event.trigger('htmlchanging', { elements: elem, content: { current: elem.html(), pending: html} });
        elem.html(html);
        jQuery.event.trigger('htmlchanged', { elements: elem, content: html });
    }
    

    Now you can subscribe divhtmlchanging/divhtmlchanged events as follow,

    $(document).bind('htmlchanging', function (e, data) {
        //your before changing html, logic goes here
    });
    
    $(document).bind('htmlchanged', function (e, data) {
        //your after changed html, logic goes here
    });
    

    Now, you have to change your div content changes through this changeHtml() function. So, you can monitor or can do necessary changes accordingly because bind callback data argument containing the information.

    You have to change your div's html like this;

    changeHtml('#mydiv', '

    test content

    ');

    And also, you can use this for any html element(s) except input element. Anyway you can modify this to use with any element(s).

提交回复
热议问题