【问题标题】:jquery find nearest class and remove itjquery找到最近的类并将其删除
【发布时间】:2012-08-14 21:26:14
【问题描述】:

如果单击特定的 delete 类,我将尝试删除整个块 list_product。我对 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();
});

不工作。我可以知道为什么以及如何解决它吗?谢谢

【问题讨论】:

标签: jquery


【解决方案1】:

只要$(this).closest('.list_product').remove()
API ref: http://api.jquery.com/closest/
find 搜索当前元素的子元素。在这种情况下,.delete 元素没有任何子元素。相反,closestup 穿过 DOM,寻找类 list_product 的第一个祖先。希望这会有所帮助。

【讨论】:

    【解决方案2】:

    试试这个:

    $(document).on('click', '.delete', function(e) {
       e.preventDefault();
       $(this).closest('.list_product').remove();
       return false;
    });
    

    【讨论】:

      【解决方案3】:

      你可以在父元素上使用event delegation或者使用Closest方法

      Closest 很容易使用:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-17
        • 2012-06-20
        • 1970-01-01
        • 2012-10-31
        • 1970-01-01
        • 2012-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多