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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:08:21  来源:igfitidea点击:

jquery find nearest class and remove it

jquery

提问by user1594367

I am trying to remove list_productentire block if that particular deleteclass 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/
findsearches through the children of the current element. In this case, the .deleteelements don't have any children. Conversely, closestgoes 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方法

Closest is pretty easy to use :

Closest 非常容易使用:

var id = $("button").closest("div").attr("id");