By right-clicking on each picture, the picture will be removed, and a new item will be created by clicking on the + button.
But the problem is that the new items that are created (appended) could not be removed. Why is this the case?
$(document).ready(function() { let nextItem = 4; $(".items div").click(function() { $(this).remove(); }); $(".btn").click(function() { $(".items").append(`<div id="${nextItem}"><img src="https://picsum.photos/id/${nextItem - 1}/200/100" alt=""></div>`); nextItem++; }) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="items"> <div id="1"><img src="https://picsum.photos/id/0/200/100" alt=""></div> <div id="2"><img src="https://picsum.photos/id/1/200/100" alt=""></div> <div id="3"><img src="https://picsum.photos/id/2/200/100" alt=""></div> </div> <button class="btn">+</button> </div>
Advertisement
Answer
Because those aren’t targeted by the event handler. It doesn’t automatically update the elements which are matching the query selector, it’s the same as if you’d used addEventHandler
– it runs once. (see below where they don’t log a message to the console but the hardcoded ones do).
$(document).ready(function() { let nextItem = 4; $(".items div").click(function() { console.log("Event processed"); }); $(".btn").click(function() { $(".items").append(`<div id="${nextItem}"><img src="https://picsum.photos/id/${nextItem - 1}/200/100" alt=""></div>`); nextItem++; }) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="items"> <div id="1"><img src="https://picsum.photos/id/0/200/100" alt=""></div> <div id="2"><img src="https://picsum.photos/id/1/200/100" alt=""></div> <div id="3"><img src="https://picsum.photos/id/2/200/100" alt=""></div> </div> <button class="btn">+</button> </div>
Instead what I would do is define that removal as a function and re-add it to the new element using the id
:
$(document).ready(function() { let nextItem = 4; function removeItem() { $(this).remove(); } $(".items div").click(removeItem); $(".btn").click(function() { $(".items").append(`<div id="${nextItem}"><img src="https://picsum.photos/id/${nextItem - 1}/200/100" alt=""></div>`); $(`#${nextItem}`).click(removeItem); nextItem++; }) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="items"> <div id="1"><img src="https://picsum.photos/id/0/200/100" alt=""></div> <div id="2"><img src="https://picsum.photos/id/1/200/100" alt=""></div> <div id="3"><img src="https://picsum.photos/id/2/200/100" alt=""></div> </div> <button class="btn">+</button> </div>