jquery 找到最近的类并将其删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11953177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery find nearest class and remove it
提问by user1594367
I am trying to remove list_product
entire block if that particular delete
class is clicked. I am very new to jquery and still learning.
list_product
如果delete
单击该特定类,我将尝试删除整个块。我对 jquery 很陌生,仍在学习。
<div class='list_product'>
<div class='row'>
<div class='delete'>x</div>
<div class='title'>Standing Fan</div>
</div>
</div>
<div class='list_product'>
<div class='row'>
<div class='delete'>x</div>
<div class='title'>Standing Fan 2</div>
</div>
</div>
<div class='list_product'>
<div class='row'>
<div class='delete'>x</div>
<div class='title'>Standing Fan 3</div>
</div>
</div>
<div class='list_product'>
<div class='row'>
<div class='delete'>x</div>
<div class='title'>Standing Fan 4</div>
</div>
</div>
Jquery:
查询:
$('.delete').click(function() {
$(this).find('.list_product').remove();
});
Is not working. may i know why and how do i fix it? thanks
不管用。我可以知道为什么以及如何解决它吗?谢谢
回答by Abraham
Just do $(this).closest('.list_product').remove()
.
API ref: http://api.jquery.com/closest/find
searches through the children of the current element. In this case, the .delete
elements don't have any children. Conversely, closest
goes upthru the DOM, looking for the first ancestor with the class list_product
. Hope this helps.
就做$(this).closest('.list_product').remove()
。
API ref:http: //api.jquery.com/closest/find
搜索当前元素的子元素。在这种情况下,.delete
元素没有任何子元素。相反,closest
去了直通的DOM,寻找具有类始祖list_product
。希望这可以帮助。
回答by mmcachran
Try this:
尝试这个:
$(document).on('click', '.delete', function(e) {
e.preventDefault();
$(this).closest('.list_product').remove();
return false;
});
回答by Amyth
You can use event delegationon the parent element or use Closestmethod
Closest is pretty easy to use :
Closest 非常容易使用:
var id = $("button").closest("div").attr("id");