简体   繁体   中英

Adding listeners to Dynamically Added Elements

I am trying to add multiple event listeners to elements that are being dynamically added to a page. I have attempted to use the on() function, as instructed in many posts but none of them seem to work for. When the page is clicked, a new should be added, with formatting determined by the correct CSS class. When a particular is focused, it should be movable using WASD and the jquery animate(). Here is what I have right now:

$(document).ready( function() {
var $index = 0;
$('div').on('keydown', 'div' , function(key) {
    switch(parseInt(key.which,10)) {
        case 87: //W
            $(this).animate({top: '-=10px'}, 'fast');
            break;
        case 65: //A
            $(this).animate({left: '-=10px'}, 'fast');
            break;
        case 83: //S
            $(this).animate({top: '+=10px'}, 'fast');
            break;
        case 68: //D
            $(this).animate({left: '+=10px'}, 'fast');
            break;
        default:
            break;
    }
});
$(document).click( function() {
    // if(key.which == 13)
    {
        var $toadd = "<div class='";
        switch($index % 4)
        {
            case 0:
                $toadd += "red' tabindex='"+ ($index + 1) + "'></div>";
                $index++;
                break;
            case 1:
                $toadd += "green' tabindex='"+ ($index + 1) + "'></div>";
                $index++;
                break;
            case 2:
                $toadd += "blue' tabindex='"+ ($index + 1) + "'></div>";
                $index++;
                break;
            case 3:
                $toadd += "yellow' tabindex='"+ ($index + 1) + "'></div>";
                $index++;
                break;
            default:
                break;
        }
        $('body').append($toadd);
        // $('body').on('click keydown','div', function() {
        //     $('body').append($toadd);
        // });
    }
});
});

Currently, the DIVs are added by clicking the page, but cant be moved using WASD. The s are focusable for the animate function to work. If I remove the dynamically adding by clicking and place a few static s, it works great.

Thanks for anything you can offer!

You need to use on() for event delegation in your case.

$(document).on('keydown', '.red, .green, .blue, .yellow' , function(key) //Instead of document use a container that exists in DOM at any given time to have the event delegated to these divs.

With this you attach the event to document head or any container that holds these divs and which inturn will be delegated to any of these divs present now or added for the future.

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