[英]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.