Binding event to dynamically created elements using jQuery

后端 未结 1 758
深忆病人
深忆病人 2020-12-21 12:34

I am uploading multiple images and placing them inside some divs which onclick have to toggle some class. Do I have to place the part in which I add the onclick event inside

1条回答
  •  囚心锁ツ
    2020-12-21 12:57

    For dynamically created element you have to use .live() However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:

    If you have greater version of jQuery than 1.9 you can use jQuery.fn.on

    I would recommend to use .on below is a signature of .on function

    $(document).on( eventName, selector, function(){} );
    
    $("body").on("click", "#YOUR_DYNAMICALLY_CREATED_ELEMENT", function(event){
        //Do Some stuff
    });
    

    Solved version:

    $("body").on('click', '.box-picture-selected > div > div', function(event)
    {
        $(this).toggleClass('image-selected');
    });
    

    0 讨论(0)
提交回复
热议问题