I have a div, which has content populated on load (a bunch of 'span' tags with a delete link in each. clicking the delete button will remove that span. Now you can also add new 'span' tags to it using a separate button (each with their own delete button). The initially loaded span delete buttons work fine, but the newly added ones do not delete.
<div class="instances">
<span class="item">Instance 1 <a href="#" class="del">delete</a></span>
<span class="item">Instance 2 <a href="#" class="del">delete</a></span>
</div>
<span class="addinstance">Add an instance</span>
$('.addinstance').click(function () {
$('.instances').append('<span class="item">More <a href="#" class="del">delete</a></span> ');
});
$('.instances .del').click(function (event) {
event.preventDefault();
$(this).parent('.item').hide();
});
Check out the fiddle I made for a working version of this: http://jsfiddle.net/Ac7x6/3/
In the fiddle:
Click the delete button on Instance 1 - works fine.
Click the 'Add an Instance' button - this adds an new entry.
Click the 'delete' button on the newly added instance - does not delete.
I have read a lot about this issue, including jquery .on(). Just not sure exactly how to implement them.
Help! :)
Use event delegation for dynamically generated items, If you wanna remove the item then use remove()
$('.instances').on('click','.del',function (event) {
event.preventDefault();
$(this).parent('.item').remove();
});
try this,
$(document).on("click", '.instances .del', function (event) {
//your code
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.