Binding a click event with AJAX-loaded content without delegating it?

I have a situation where I use an attribute datawith a name data-commandin many cases in a specific section of the site and instead of linking tons of individual click events, I decided to use it and use a switch for example:

$('[data-command]').on('click', function(event) {

    // Prevent default click action
    event.preventDefault();

    // Get command
    var command = $(event.target).data('command');

    switch (command) {
        // Do stuff...
    }

    // Prevent default click action (IE 8)
    return false;

});

However, this only became a problem when trying to get it to work with data loaded through AJAX.

This obviously works.

$('#existing_element').on('click', '[data-command]', function(event) {

... but since it should work on different pages in this section of the site, it will not work on all pages.

id , ajax, .

, .

$(document).on('click', '[data-command]', function(event) {

... , , , .

: Html DOM jQuery html.

, , ?

+4
1

- . , .

$('[data-command]').off('click').on('click', clickHandler);

// Somewhere in the same scope
function clickHandler(e) {
    // Handle click event here
}

html().

off('click') , , on('click', , .


Edit

, . ?

, DRY , , .

function clickHandler(e) {
    // Handle click event here
}

function bindEvent() {
    $('[data-command]').off('click').on('click', clickHandler);
}

$(document).ready(bindEvent);

...

$.ajax({
    ...
    success: bindEvent
....
+2

Source: https://habr.com/ru/post/1608995/


All Articles