繁体   English   中英

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

[英]Get the first previous element that matches a condition with Jquery

我有这个表,我怎么能得到第一个具有.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

请帮助

我建议使用prevAll结合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> 

使用prevUntil()

 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> 

暂无
暂无

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

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