简体   繁体   中英

Triggering an event when an element is created

I wanna call a function on creation of new divisions in the DOM (ie created dynamically thru ajax call) .I know I can use live method for triggering the function. But what event should I use in the live method ? I mean which even would be triggered when a new division is dynamically created?

You can use the DOMNodeInserted mutation event, but be aware that they are deprecated and not supported in all browsers.

Better solution would be to write a custom event like:

$('#container').bind('MyAddEvent', function(){
    alert('Was added');
});

If you want the event to be applied to new elements as well, use on :

$('#container').on('MyAddEvent', '{selector}' ,function(){
    alert('Was added');
});

And when you add new <div> (after ajax requests), Trigger that event with trigger :

...
success: function(result){
    $('#container').append(result)
    ...
    ...
    $('#container').trigger('MyAddEvent');
} 
  • Note that live is deprecated, on is the new guy.

If you don't control the new div s insertion , you can inspect the DOM on each x time for new divs:

function checkForChanges()
{
    var newDivs = $('#container div').filter(function(){
            return !$(this).data('old')
        });

    ... //Do what you want with those divs      

    newDivs.data('old', true); // mark the div as old.

    setTimeout(checkForChanges, 1000); // Check the DOM again within a second.
}

$(checkForChanges);

Detect DOM changes with Mutation Observers demos DOM4 Mutation Observers (Webkit only, at the moment). So for now, you're quite screwed. DOMNodeInserted is not available in every browser, and where it is available, it is awful slow. Mutation Observers are much faster, but currently only available in Webkit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM