如何使用jquery到达叔叔

Ali*_*sam 10 html jquery parents dom

<div id="grandfather">
  <div id="uncle"></div>
  <div id="father>
    <div id="me"></div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我在$("#me"),我想选择我的叔叔,使用类似的东西:

 $("#me").find("#uncle")
 $("#me").next("#uncle")
 $("#me").prev("#uncle")
Run Code Online (Sandbox Code Playgroud)

怎么样 ?

Sam*_*son 22

你可以使用$.parent$.prev假设你的叔叔总是高于你的父亲:

$(this).parent().prev(); // where 'this' is #me
Run Code Online (Sandbox Code Playgroud)

你也可以一直到你的祖父,并从那里找到叔叔:

$(this).parents("#grandfather").find(".uncles");
Run Code Online (Sandbox Code Playgroud)

或者你可以搜索你父亲的兄弟姐妹:

$(this).parent().siblings("#uncle");
Run Code Online (Sandbox Code Playgroud)

我建议您阅读jQuery API 的Traversing部分以了解各种其他方法.