开发者

Jquery - How do I start a function when div content is changed

开发者 https://www.devze.com 2023-01-11 13:35 出处:网络
I searched for a solution like: if( content from $(\'#div\') is change -> start function test(); ) 开发者_开发百科

I searched for a solution like:

if( content from $('#div') is change -> start function test(); )
开发者_开发百科

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

Thanks in advance! Peter

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


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

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

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


Just chain .test() on after .html.

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

To achieve this, simply make a little plugin.

Like this (jsFiddle example):

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

That return is needed, since a method must return the jQuery object, unless explicity noted otherwise for a jQuery plugin. Read about jQuery plugins here.


It can be done 2 ways 1) create new jquery method and call your test function before calling jquery hml function. So instead of $('#div').html('blub') you will write $.myhtml($("#div").html()). Code below might give you some idea(Got it working)

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

2) override jquery html function 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);
    });
};


Just out of curiosity, if you are changing the div content with your code, couldn't you just call test() when you change the div?

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


This will do the job $('#div').change(function(){ test(); });

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号