Click on dynamically generated element does not work

0

Hi, I am cloning an element via jQuery and when I click on an item of the cloned element the click does not work, it follows example codes:

Cloning:

var template = $(".products .product.template").clone().prependTo($(".products")).removeClass("template");

Click on the element:

$(".remover").click(function(e) {
    console.log("teste");
    e.stopPropagation();
    return false;
});

This remove class is inside the template of the first code sample (cloning).

    
asked by anonymous 06.05.2018 / 04:39

1 answer

2

You must use .clone(true) as described in the documentation: link

  

.clone ([withDataAndEvents])

     

A Boolean that indicates whether event handlers should be copied together with the elements. From jQuery 1.4, the element data will be copied as well.

Example:

var bar = $('.foo .bar');

bar.click(function () {
    console.log(Date.now());
});

var clonado = bar.clone(true);

clonado.appendTo('.baz');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h1>Copiado.barde.foopara.baz:</h1><divclass="foo">
Original: <div class="bar">Click em foo</div>
</div>

<hr>

<div class="baz">
Copiado:
</div>

Delegating events

Another way to get the desired result is by delegating events, for example you set .click to document , but informs that the expected object is .baz (example only) and then all elements that are added at any time will have the click event, ie everything from document , example:

var bar = $('.foo .bar');

//O evento click de document será delegado para todos ".bar"
$(document).on('click', '.bar', function () {
    console.log(Date.now());
});

setInterval(function () {
    var clonado = bar.clone();

    clonado.appendTo('.baz');
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h1>Copiado.barde.foopara.baz:</h1><divclass="foo">
Original: <div class="bar">Click em foo</div>
</div>

<hr>

<div class="baz">
Copiados:
</div>
    
06.05.2018 / 04:59