2014-02-18 93 views
2

我正在寻找这个简单答案的小时。我有5个图像的上传领域,我想为每个上传的图像做一个删除按钮。如果你点击这个按钮,最近的图像需要删除。删除最近上传的图片

我知道堆栈上有很多关于此项目的问题,但无法找到合适的问题。我试过closest()find(),closest()children(),但无法使其工作。

有人能给我正确的提示吗?

我做了一个的jsfiddle:http://jsfiddle.net/4SHUG/

这是我的html:

<div class="stn_uploader"> 
    <p class="delete">Delete</p> 
    <img src="http://3.bp.blogspot.com/-hME1fzYTKkc/Tl157uRJ3gI/AAAAAAAAIzQ/OnqAvShZaLA/s1600/white-clouds.jpg" width="300"/> 

</div> 

<div class="stn_uploader"> 
    <p class="delete">Delete</p> 
    <img src="http://3.bp.blogspot.com/-hME1fzYTKkc/Tl157uRJ3gI/AAAAAAAAIzQ/OnqAvShZaLA/s1600/white-clouds.jpg" width="300"/> 

</div> 

<div class="stn_uploader"> 
    <p class="delete">Delete</p> 
    <img src="http://3.bp.blogspot.com/-hME1fzYTKkc/Tl157uRJ3gI/AAAAAAAAIzQ/OnqAvShZaLA/s1600/white-clouds.jpg" width="300"/> 

</div> 

这是我的jquery:

$(document).ready(function() { 

    $('.stn_uploader .delete').click(function() { 
      $(this).closest('.img').remove(); 
    }); 

}); 

回答

4

图像是兄弟,因此closest()将无法​​正常工作。您可以使用next()

使用

$(document).ready(function() { 
    $('.stn_uploader .delete').click(function() { 
      $(this).next('img').remove(); 
    }); 
}); 

OR

$(document).ready(function() { 
    $('.stn_uploader .delete').click(function() { 
      $(this).closest('.stn_uploader').find('img').remove(); 
    }); 
}); 
+0

谢谢!接下来不起作用,但.closest().find()会! – Robbert

+0

@Robbert,接着也适用见[__demonstration__](http://jsfiddle.net/4SHUG/1/) – Satpal

+0

呀被看到。但我已经在同一个jsfiddle中尝试过,并没有工作。但现在呢! – Robbert

1

IMG是兄弟姐妹,最近着眼于自身及其祖先。第二个问题是您selecotr是错误的,你正在寻找一类 “IMG”,而不是一个元素 “IMG”

您可以使用next()

$(this).next().remove(); 

siblings()

$(this).siblings("img").remove(); 

或如果你想删除整个块,最接近的工作。

$(this).closest('.stn_uploader').remove(); 
0

closest向上遍历DOM树并获得第一个匹配的祖先。

对于您的情况,img是您的段落的下一个元素。所以,你需要使用next()siblings()

$('.stn_uploader .delete').click(function() { 
     $(this).next().remove(); // or $(this).siblings('.img').remove(); 
}); 

顺便说一句,你的图像没有命名为img任何类,如果你想针对<img>标签,你可以使用:

$('.stn_uploader .delete').click(function() { 
    $(this).siblings('img').remove(); 
}); 
0

为什么你是否使用(“.img”)。img tag.Try中没有类。

$(document).ready(function() { 

    $('.stn_uploader .delete').click(function() { 

      $(this).next('img').remove(); 
    }); 

}); 

OR

$(document).ready(function() { 

     $('.stn_uploader .delete').click(function() { 

       $(this).parent('.stn_uploader').remove(); 
     }); 

    }); 
0

你并不遥远;)

$('.stn_uploader .delete').click(function() { 
    $(this).closest('.img').remove(); 
}); 

首先,您使用的是类.img而不是元素节点名称img

然后,img是兄弟不是父元素,所以如果你从.delete想找到它,你应该使用next

$('.stn_uploader .delete').click(function() { 
    $(this).next('img').remove(); 
}); 

我想你也应该看看该选项删除整个容器:

$('.stn_uploader .delete').click(function() { 
     $(this).parent().remove(); 
});