简体   繁体   English

jQuery最近的()到达具有特定类或ID的行上方

[英]jQuery closest() getting above row with a certain class or id

The following is a simplified example to explain what I am trying to understand, namely how to get the first row above the current row that has a certain id: 以下是一个简化的示例,用于解释我试图理解的内容,即如何使具有特定ID的当前行上方的第一行:

<script>
$(document).ready(function(){
  $("#alphabet").closest("tr']").css({"color": "white", "background-color": "green"}); // finds the same row as expected
  $("#alphabet").closest("tr#number']").css({"color": "white", "background-color": "green"});  // Does NOT find anything
  $("#alphabet").closest("tr:has([class*='num'])").css({"color": "white", "background-color": "green"}); // Does NOT find anything

});
</script>
</head>

<body >body (great-great-grandparent)
  <table>
    <thead>
      <tr>
          <th>col 1</th>
          <th>col 2</th>
      </tr>
  </thead>
    <tbody>
      <tr id='number' class="num">
          <td>1</td>
          <td>2</td>
      </tr>
      <tr id='alphabet'>
          <td>a</td>
          <td>b</td>
      </tr>
    </tbody>
  </table>

</body>

I am intentionally avoiding the use of .next(), prev(). 我故意避免使用.next(),prev()。

try: 尝试:

$("#alphabet").siblings('#number').css(...)

Closest is for moving up the hierarchy, eg from td to tr, siblings for moving around same level. 最近是用于将层次结构(例如,从td移至tr)向上移动,而兄弟姐妹则用于在同一级别上移动。

Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. 给定一个表示一组DOM元素的jQuery对象,.closest()方法将在DOM树中搜索这些元素及其祖先,并从匹配的元素构造一个新的jQuery对象。 The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. .parents().closest()方法的相似之处在于它们都遍历DOM树。 The differences between the two, though subtle 两者之间的差异虽然微妙

May be best to use .parents() or .siblings() . 最好使用.parents().siblings() .closest() will not be able to see the element as it will have already traverse to <tbody> in it's first step. .closest()将无法看到该元素,因为在第一步中该元素已经遍历<tbody>

 $(function() { $("#alphabet").parent().find("#number").css({ "color": "white", "background-color": "green" }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <thead> <tr> <th>col 1</th> <th>col 2</th> </tr> </thead> <tbody> <tr id='number' class="num"> <td>1</td> <td>2</td> </tr> <tr id='alphabet'> <td>a</td> <td>b</td> </tr> </tbody> </table> 

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

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