Hello, I at the touch of a button create a new div, inside which there is a button. Can you please tell me how to handle it?

$("#btn2").click(function () { var dynDiv = $('<div>') .attr('id', 'div_' + dname_id++) .css({ 'width': '50px', 'height': '20px' }) .addClass('resize') .html("<button id='dbtn' >click</button>"); $('#dbtn').click(function () {alert("ghj")}) $('#container').append(dynDiv); //-------------------------------------------------------// dynDiv.click(function () { $('.selected').removeClass('selected'); $(this).addClass('selected'); }); }); 

I tried, but without success. Thanks in advance!

    2 answers 2

    Dynamically added elements can be subscribed to events using the jQuery function .on ' $(selector).on('eventname', function(e){ ... '

     var dname_id = 1; $("#btn2").click(function () { var dynDiv = $('<div>').attr('id', 'div_' + dname_id++) .css({ 'width': '50px', 'height': '20px' }).addClass('resize').html("<button id='dbtn' >click</button>"); $('body').append(dynDiv); //1. append html fragment to DOM // 2. add event listener $('#dbtn').on('click', function () { alert("ghj"); }); dynDiv.click(function () { $('.selected').removeClass('selected'); $(this).addClass('selected'); }); }); 

    working example: http://jsfiddle.net/93m1fLzr/1/

    • And if, for example, objects, are images loaded on ajax per page, how to process them? The click is understandable, also, and if I need for example such $ ("img"). Resizable (); This doesn’t work on ajax images - zkolya

    It should be like this:

     $('body').on('click', '#dbtn', function(){ alert('good'); }) 

    but if there are a lot of buttons then you need to use id instead of id

    • Thank you very much! - zkolya
    • Not at all, always happy) - Maks Devda