jquery event after html() function

前端 未结 5 1128
情话喂你
情话喂你 2021-01-11 19:05

Is there a way to launch an event after html() has been fired? Such as:

$.post(\"ajax.php\", {data :data}, function(data){
   $(\"#countries\").html(data, fu         


        
相关标签:
5条回答
  • 2021-01-11 19:31

    This syntax may also be of interest to you:

    $(selector).html(function(index,oldHTML){
        alert("test");
        return data;
    });
    
    0 讨论(0)
  • 2021-01-11 19:36

    Yes you can...

    // create a reference to the old `.html()` function
    var htmlOriginal = $.fn.html;
    
    // redefine the `.html()` function to accept a callback
    $.fn.html = function(html,callback){
      // run the old `.html()` function with the first parameter
      var ret = htmlOriginal.apply(this, arguments);
      // run the callback (if it is defined)
      if(typeof callback == "function"){
        callback();
      }
      // make sure chaining is not broken
      return ret;
    }
    
    // test it all works as expected (including chaining)
    $("#mything").html("<div>My Thing</div>",function(){
      console.log("Just did my thing");
    }).css({color: 'red'})
    

    However, like everyone else says, it is unnecessary as .html() is synchronous, so you can just put your code following it rather than in a callback.

    Demo: http://jsfiddle.net/billymoon/a49P4/

    0 讨论(0)
  • 2021-01-11 19:37

    No but there is no reason you couldn't do this:

    $.post("ajax.php", {data :data}, function(data){
       $("#countries").html(data);
       var id = $("#countries option:selected").attr("id");
       getRegions(id);
    });
    
    0 讨论(0)
  • 2021-01-11 19:43

    html() is a synchronous operation, not an event, and so it would not logically accept a callback.

    Just put your code after it:

    $('container').html(data);
    alert('test');
    
    0 讨论(0)
  • 2021-01-11 19:48

    You can include the javascript code in your html response. An inline example:

      $("#content").html("hello\<script>\alert('hello');\</script\>");​
    

    would update the div and also execute the code.

    0 讨论(0)
提交回复
热议问题