简体   繁体   English

选择相邻元素的子元素

[英]Selecting a child element of an adjacent element

I'm attempting to use .parents to select an element in an adjacent ul so that I can click one to affect the other. 我正在尝试使用.parents在相邻ul中选择一个元素,以便可以单击其中一个元素来影响另一个元素。

I can select the parent .outside of both ul, starting from the span within .ulB however when I ask it to go back in and select .ulA it doesn't like it. 我可以从.ulB中的跨度开始选择两个ul的父.out,但是当我要求它返回并选择.ulA时,它不喜欢它。

Any ideas? 有任何想法吗? It is possible to do this using this method or at all? 可以使用此方法执行此操作,还是完全可以执行此操作? Thanks. 谢谢。

Example code below. 下面的示例代码。

<!DOCTYPE html>
<html>
<head>

<style>
  .ancestors * { 
  display: block;
  border: 2px solid lightgrey;
  color: lightgrey;
  padding: 5px;
  margin: 15px;}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("span").parents(".outside > .ulA").css({"color": "red", "border": "2px solid red"});
});
</script>

</head>

<body class="ancestors">
  <div class="outside" style="width:500px;">

    <ul class="ulA">  
      <li></li>
    </ul>

    <ul class="ulB">
      <li>
        <span>span</span>
      </li>
    </ul>

  </div>
</body>

</html>

There's no parent of a span matching .outside > .ulA . 没有匹配.outside > .ulAspan的父.outside > .ulA You need to find the parent first, then find the .ulA descendant: 您需要先找到父级, 然后再找到.ulA后代:

$("span").
  parents(".outside").
  find(".ulA").
  css({"color": "red", "border": "2px solid red"});

  $("span").parents(".outside").find(".ulA").css({ "color": "red", "border": "2px solid red" }); 
  .ancestors * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="ancestors"> <div class="outside" style="width:500px;"> <ul class="ulA"> <li></li> </ul> <ul class="ulB"> <li> <span>span</span> </li> </ul> </div> </div> 

The parents selector does not exist. 父选择器不存在。

You first need to find the parent and then search within it. 您首先需要找到父对象, 然后在其中搜索。

Also - use closest . 也可以使用closest You don't need parents (unless filtering later) , and also it's faster than parent . 您不需要parents (除非稍后进行过滤),而且它比parent更快。 closest already returns the first match. closest已经返回第一个匹配项。

$("span").closest(".outside").find(".ulA").css({"color": "red", "border": "2px solid red"});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM