我有这个表,如何获取第一个具有 .cep 类的预处理器并使用 Jquery 获取此元素?
这是我的 table :
<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>
关于javascript - 使用 Jquery 获取与条件匹配的第一个前一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31733894/