簡體   English   中英

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

[英]jQuery closest() getting above row with a certain class or 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>

我故意避免使用.next(),prev()。

嘗試:

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

最近是用於將層次結構(例如,從td移至tr)向上移動,而兄弟姐妹則用於在同一級別上移動。

給定一個表示一組DOM元素的jQuery對象,.closest()方法將在DOM樹中搜索這些元素及其祖先,並從匹配的元素構造一個新的jQuery對象。 .parents().closest()方法的相似之處在於它們都遍歷DOM樹。 兩者之間的差異雖然微妙

最好使用.parents().siblings() .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