Cannot get jQuery on () to register dynamically added content

I'm new to the on () method in jQuery, but it's time to use it.

I have two functions for clicking on specific buttons. Each function works with any elements that were originally on the page, but not on any dynamically added content (more of the same buttons). I understand that I need to use the on () function after reading the other answers here and on Google, but I still have problems. Anyway, the code:

jQuery("ul#THEBUTTONS").on({
    click: function(event){
        event.preventDefault();
        console.log("apaz clicked");
    }
}, "a.azaz");


jQuery("ul#THEBUTTONS").on({
    click: function(event){
        event.preventDefault();
        console.log("mapaz clicked");
    }
}, "a.mapaz");

Any help would be greatly appreciated, tearing my hair off here.

+5
source share
2 answers

.on() : , .bind(), .delegate().

delegate. , on :

// bind
$(element-selector).on(event, handler)

// delegate
$(container-selector).on(event, element-selector, handler)

- , , delegate, , , on.

+8

.on(), .

$('selector for elements you want the event handler bound to').on('event', function() {...});

, .on() -, , div , , <body>. :

<div id="wrapper">
    <a href="#" class="link">Test link</a>
</div>

$('#wrapper').on('click', '.link', function(e) {
    // code to handle the click event on the link here
});

<div id="wrapper"> , , , . link div, .

+1

All Articles