简体   繁体   中英

Jquery: click event to remove() image element click on and adjacent image element

This is prob a quite weird or simple error. But it's doing my head in lol. The code below is a click event handler aimed at 2 <img> elements. You click on the one <img> element classed "undo" - This should remove the <img> being clicked and also the element classed "bin" directly next to it at the same time. I manage to either the one or the other removed but not both. Can anyone help please? Thank you Walter

JS:

$('ul').on('click','.undo',function(e) {
    $(this).remove();   
    $(this).prev().remove();

HTML:

<img src="images/bin.png" align="right" class="bin">
<img src="images/undo.png" align="right" class="undo">

Once you call $(this).remove(); , the element is removed from the dom, thereafter $(this).prev() will not find any element as there won't be any previous sibling for the detached element

$('ul').on('click', '.undo', function (e) {
    $(this).prev().addBack().remove();

Or

$('ul').on('click', '.undo', function (e) {
    $(this).prev().remove();
    $(this).remove();

Swap the removal process instead as below:

$('ul').on('click','.undo',function(e) {
    $(this).prev().remove(); 
    $(this).remove();   
});

DEMO

What you are doing here is trying to remove the previous element once the current element has been removed and jquery will not be able to find this element once removed, to remove its previous element. So just remove its previous element first and then remove the current element.

I played around with the rest of my code and realised the problem lies there. The problem comes in with bubbling effect and that the items were added after the page loaded via the DOM.

Thanks for looking into - I need to go analyse other bits of my code causing this not to work.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM