JQuery - How to start a function when changing the contents of a div

I was looking for a solution like:

if( content from $('#div') is change -> start function test(); )

I am changing the content with $('#div').html('blub');

Thanks in advance! Peter

PS: I know this is possible with setTimeout, but this is a really dirty solution: /

+3
source share
5 answers

Just chain .test () after after .html.

$('#div').html('blub').test();

To achieve this, just create a small plugin.

Like this (jsFiddle example) :

jQuery.fn.test = function() { 
    // Your test function goes here. 
    return this.each()};

This return is necessary because the method should return a jQuery object, unless otherwise specified explicitly for the jQuery plugin. Read about jQuery plugins here .

0
source

I think the best way to achieve this is to write a custom html function, something like this:

function changeHtml(content) {
    this.html(content);
    yourChangeHandler(this);
}

: ... http://forum.jquery.com/topic/what-is-the-best-way-to-handle-onchange-event-on-a-div

+2

1) jquery jquery hml. $('# div').html('blub') $. Myhtml ($ ( "# div" ). Html()). ()

**jQuery.extend(jQuery, { myhtml: function (arg1, html) { 
         test();
       return arg1.html(html); 
} });** 
 call by $.myhtml($("#div"), $("#div").html()) or $.myhtml($("#div"))

2) jquery html http://www.bennadel.com/blog/1624-Ask-Ben-Overriding-Core-jQuery-Methods.htm

var refhtml = $.fn.html;

$.fn.html = function() {
    $(this).each(function() {
       test();
        refhtml .apply(this, arguments);
    });
};
0

, div , test(), div?

$().event(function(){
    $('#div').html('blub');
    test();  //call your test function
});
-1

 $('#div').change(function(){ test(); });

-1

Source: https://habr.com/ru/post/1759873/


All Articles