DD! There is such a problem: I create a function on the page with a function, and with another function I try to set actions on the created element:

$("#addspoint").click(function() { $("#gamecoord").append(itog+'<i class="icon-bucket" id="ssdd"></i> <br>'); }); $("#ssdd").click(function() { alert('sdadasd'); }); 

On the page, the elements are normally created, but the action when clicking on the elements does not occur. Why and how to fix it?

  • Do fiddle? - Sergiks

4 answers 4

 //эта функция выполняется через 0 милисекунд после загрузки страницы $("#addspoint").click(function() { //это действие выполняется после клика $("#gamecoord").append(itog+'<i class="icon-bucket" id="ssdd"></i> <br>'); }); //эта функция выполняется через 1 милисекунду после загрузки страницы //на этот момент никакого #ssdd на странице не существует //поэтому клик никуда не привязывается $("#ssdd").click(function() { alert('sdadasd'); }); 

Here's how:

 $("#addspoint").click(function() { //сначала создали элемент $("#gamecoord").append(itog+'<i class="icon-bucket" id="ssdd"></i> <br>'); //потом привязали к нему листенер $("#ssdd").click(function() { alert('sdadasd'); }); }); 
     $(document).on('click', '#ssdd', function() { console.log('click'); }); 
    • It is worth mentioning that this is true for jQuery versions> = 1.7 - Sergiks
    • Try to write more detailed answers. You can explain the solution, point out specific errors, provide links with a more detailed analysis of the problem, etc. - Athari

    You are assigning an event when there is no item yet. When an item is created, there is no reason why it would listen to an event.

    Bind the event listener after the item is created.

    With minimal changes in your code, you just need to move the last three lines up one line:

     $("#addspoint").click(function() { $("#gamecoord").append(itog + '<i class="icon-bucket" id="ssdd"></i> <br>'); $("#ssdd").click(function() { alert('sdadasd'); }); }); 

    Feeddle

      Well, as an option in the treasury of solutions

       $("#addspoint").click(function() { var $el = $(itog+'<i class="icon-bucket" id="ssdd"></i> <br>'); $el.on('click', function() { console.log('I am here'); }); $("#gamecoord").append($el); });