jQuery event when element is created

前端 未结 2 754
情话喂你
情话喂你 2021-02-13 20:22

I\'d like to trigger an event when an element is created.

$(document).on(\'load\',\'#TB_title\',function() {
    console.log(\'loaded\');
});

I

相关标签:
2条回答
  • 2021-02-13 20:58

    You can trigger a global custom event:

    $(document).on('load','#TB_title',function() {
      $.event.trigger('nameOfCustomEvent');  
    });
    
    $('#element').bind('nameOfCustomEvent', function(){
      console.log(this);
    });
    
    0 讨论(0)
  • 2021-02-13 21:09

    I don't think such thing exist directly, but you can handle the DOMSubtreeModified event and wait until you can find element with such ID:

    var _elementToFind = "TB_title";
    var _elementFound = false;
    var _counter = 1;
    $(document).bind("DOMSubtreeModified", function(evt) {
        if (_elementFound)
            return;
        if ($("#" + _elementToFind).length > 0) {
            alert("element '" + _elementToFind + "' created");
            _elementFound = true;
        }
    });
    

    Live test case.

    The downside is that it's not supported by Opera and IE less than 9 - see here the full details.

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