当前位置: 代码迷 >> JavaScript >> 获取与Jquery匹配条件的第一个前一个元素
  详细解决方案

获取与Jquery匹配条件的第一个前一个元素

热度:86   发布时间:2023-06-05 14:12:28.0

我有这个表,我怎么能得到第一个具有.cep类的前导并用Jquery获取这个元素?

这是我的表:

<table>
    <tr class="cep"></tr>
    <tr class="ptype"></tr>
    <tr class="item"></tr>
    <tr class="cep"></tr> (I want to get this element)
    <tr class="ptype"></tr>
    <tr class="item"></tr>
    <tr class="item-here"></tr> (I'me here)
    <tr class="item"></tr>
</table>

有没有办法做到这一点:

$('tr.item-here').prevUntilFindThefirstMatchOf('tr.cep'); Get this element

请帮助

我建议使用结合first prevAll将按选择器过滤所有以前的兄弟姐妹,并first抓住它遇到的第一个兄弟姐妹。

$('tr.item-here').prevAll('tr.cep').first();

 var meh = $('tr.item-here').prevAll('tr.cep').first(); console.log($(meh).text()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr class="cep"><td>This should not print in console</td></tr> <tr class="ptype"></tr> <tr class="item"></tr> <tr class="cep"><td>This should print in console</td></tr> <tr class="ptype"></tr> <tr class="item"></tr> <tr class="item-here"></tr> <tr class="item"></tr> </table> 

使用

 console.log($('tr.item-here').prevUntil('tr.cep').last().prev()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <table> <tr class="cep">cep</tr> <tr class="ptype">ptype</tr> <tr class="item">item</tr> <tr class="cep">cep</tr> <tr class="ptype">ptype</tr> <tr class="item">item</tr> <tr class="item-here">item-here</tr> <tr class="item">item</tr> </table> 

  相关解决方案