简体   繁体   中英

Assign click-event on a new element in the event itself

I want to create a new element and assign this element the same event for onclick, which it has created it.

DEMO

$(function(){
    var counter = 0;
    $('.sub').click(function(event){
        event.stopPropagation();
        counter++;
        $div = $(this); // makes more sense in the original code
        $div.append('<div class="sub" title="subsub">subsub' + counter + '</div>');
        //$div.find('.sub').click // <-- ?????
    });
});

In my demo I want to create a new subsub for every sub, which was clicked. Than I want to add the same click event to the new subsub element.

Could anyone help me with this? I've found nothing for this problem. Maybe I don't have the correct keywords for google or SO :/

Just use event Delegation

 $(document).on('click', '.sub', function(event){

Your click events seem to be working correctly at this point,because you are using append which actually nests the new div inside the div that is clicked. Try using after and the functionality breaks.

$(function(){
    var counter = 0;
    $(document).on('click', '.sub', function(event){
        event.stopPropagation();
        counter++;
        $div = $(this); // makes more sense in the original code
        $div.after('<div class="sub" title="subsub">subsub' + counter + '</div>');
    });
}); 

Check Fiddle

Why not create proper elements instead :

$(function(){
    var counter = 0;
    $('.sub').on('click', doStuff);

    function doStuff(event) {
        event.stopPropagation();
        counter++;
        var $div = $(this),
            $sub = $('<div />', {'class':'sub',
                                 title  : 'subsub',
                                 text   : 'subsub' + counter,
                                 on     : {
                                            click : doStuff
                                          }
                                }
        );

        $div.append($sub);
    }
});

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