How can I call a function after an element has been created in jquery?

前端 未结 9 2143
野趣味
野趣味 2020-12-28 13:37

I want to call a function after an element has been created. Is there a way to do this?

Example:

$(\"#myElement\").ready(function() {
    // call the         


        
相关标签:
9条回答
  • 2020-12-28 14:19
    $("<div id=\"elem\"></div>").appendTo("#parent").each(function(){
    
       console.log("I have been created!");
    
    });
    
    0 讨论(0)
  • 2020-12-28 14:27

    You can use setInterval function to check the existence of an element. Once the function runs, you can clear the interval:

    var CONTROL_INTERVAL = setInterval(function(){
        // Check if element exist
        if($('#some-element').length > 0){
            // ...
            // Since element is created, no need to check anymore
            clearInterval(CONTROL_INTERVAL);
        }
    }, 100); // check for every 100ms
    
    0 讨论(0)
  • 2020-12-28 14:28

    How are you creating the element?

    If you're creating it in the static HTML then just use .ready(handler) or .on("load", handler). If you're using AJAX though that's another kettle of fish.

    If you're using jQuery's load() function then there's a callback you can run when the contents been loaded:

    $('#element').load('sompage.html', function(){ /* callback */ });
    

    If you're using jQuery's $.ajax or $.get/$.post functions then there's a success callback in that:

    $.ajax({
      url: 'somepage.html',
      success: function(){
        //callback
      }
    });
    

    If you're just creating the element and appending it like this:

    $('body').append('<div></div>');
    

    Then you can do this instead:

    $('<div />', { id: 'mydiv' }).appendTo('body').ready(function(){ /* callback */ });
    

    But this won't matter - because it's synchronous (which means that the next line of code won't run until it's added the element to the DOM anyway... - unless you're loading images and such) so you can just do:

    $('<div />', { id: 'mydiv' }).appendTo('body');
    $('#mydiv').css({backgroundColor:'red'});
    

    But acctually, saying THAT you could just do this:

    $('<div />', {id:'mydiv'}).appendTo('body').css({backgroundColor:'red'});
    
    0 讨论(0)
提交回复
热议问题