Remove parent div by class name - jquery

前端 未结 5 1522
别那么骄傲
别那么骄傲 2021-01-14 20:58

I have a remove link that will remove the current comment on my page. It uses ajax to change the database and upon success, I want to remove the div the comment resides in.

相关标签:
5条回答
  • 2021-01-14 21:39

    It should be

    $(this).parent().parent().remove();
    
    0 讨论(0)
  • 2021-01-14 21:53

    You'd be better off tackling this by setting an ID for the comment in your code.

    For example:

    <div class="aComment" data-comment-id="5">
    

    Then using this ID with your AJAX request and response.

    A little more work, but it's more robust (IMO)

    0 讨论(0)
  • 2021-01-14 21:54

    Within your Ajax callback this does not refer to the anchor element, but even if it did, the .parent() method returns the immediate parent, i.e., the span element, not the div.

    Assuming you have a reference to the anchor, you can say:

     $theAnchor.parent().parent().remove();  // get a's parent's parent
    

    ...but of course that is kind of brittle because if you later change the html structure you have to change the code to. So it is better to use .closest() to search up the tree to the nearest ancestor element that matches:

    $theAnchor.closest("div").remove();
    

    You don't show your click handler, but it'll need to be something like this:

    $(".aComment a").click(function() {
       // keep a reference to the clicked a element for use
       // in the ajax callback
       var $theAnchor = $(this);
    
       $.ajax(/* your ajax parameters here */, function() {
          $theAnchor.closest("div").remove();
       });
    });
    
    0 讨论(0)
  • 2021-01-14 21:57

    Use closest():

    $(this).closest(".aComment").remove();
    

    Example.

    The parent of the a tag is the span. The div you are trying to remove is the parent of that span.

    The reason for using this is simply because it's more convenient than using parent() twice.

    0 讨论(0)
  • 2021-01-14 21:57

    If you're trying to remove it on a click:

    $(".aComment a").on('click', function(){
        $(this).closest(".aComment").remove();
    });
    

    http://jsfiddle.net/gaQuu/

    0 讨论(0)
提交回复
热议问题