jquery traversing to find a parent's parent

前端 未结 7 548
谎友^
谎友^ 2021-01-14 08:58

HTML:

  • 相关标签:
    7条回答
    • 2021-01-14 09:35

      You may use closest(). Try this:

      $(this).closest("li.comment");
      
      0 讨论(0)
    • 2021-01-14 09:38
      $("a.del").click(function() {
          alert($(this).closest("li").attr("class"))
       })
      
      0 讨论(0)
    • 2021-01-14 09:48

      .parent() by itself just refers to the immediate ancestor of a node, but you can also do:

      var li = $('a.del').parents('li.comment');
      

      to have JQuery go back up the DOM tree until it finds a matching ancestor node. In this case, li will point at the a's li ancestor.


      edit: forgot that .parent() only goes up one level, while .parents() goes up the entire tree. Both accept a selector argument, however.

      0 讨论(0)
    • 2021-01-14 09:59
      var p = $('.del').parents('li');
      console.log(p);
      

      http://jsfiddle.net/hZY8R/

      The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.

      As you can see, when you use parents with a selector, you will be fine.

      0 讨论(0)
    • 2021-01-14 09:59

      Use the following code:

      $(function(){
          $("a").click(function(){
              $(this).parents("li").hide();
          })
      })
      

      http://jsfiddle.net/4yCux/1/

      0 讨论(0)
    • 2021-01-14 10:00

      You should use closest() which will traverse up the DOM until it finds the element you're after:

      $('a').closest('li');
      

      If you were doing this the other way around (i.e. you had the li and wanted to find the a) you would use:

      $('li').find('a');
      
      0 讨论(0)
    提交回复
  • 热议问题