简体   繁体   English

jQuery选择前一个元素与选择器匹配的每个元素

[英]jquery select each element who's previous element matches selector

I have the following question and I ve been struggling with it for quite a while. 我有以下问题,并且我已经为此苦苦挣扎了一段时间。 Im sure the solution is very simple but still I cant see it. 我确定解决方案非常简单,但我仍然看不到它。 In the following set of rows I want to select only the ones which contain class .replace or .empty or .delete or .insert and are preceded by rows which contain class .equal: 在下面的行集中,我只想选择包含.replace或.empty或.delete或.insert类的行,并在前面添加包含.equal类的行:

<tr>
    <th>sth</th>
    <td class="equal"> sth</td>
    <th>sth</th>
    <td class="equal"> sth</td>
</tr>
<tr>
    <th>sth</th>
    <td class="equal"></td>
    <th>sth</th>
    <td class="equal"></td>
</tr>
<tr>
    <th>want to be 1st selected row</th>
    <td class="replace"></td>
    <th></th>
    <td class="replace"> </td>
</tr>
<tr>
    <th>dont want this one but it selects it</th>
    <td class="replace"></td>
    <th>sth</th>
    <td class="replace"> sth</td>
</tr>
<tr>
    <th>sth</th>
    <td class="equal"></td>
    <th>sth</th>
    <td class="equal"></td>
</tr>
<tr>
    <th>want to be 2nd selected row</th>
    <td class="delete"></td>
    <th></th>
    <td class="delete"> </td>
</tr>
<tr>
    <th>sth</th>
    <td class="replace"></td>
    <th>sth</th>
    <td class="replace"> sth</td>
</tr>

So Ive come up with this as a jQuery( "prev + next" ) selector but it doesnt seem to work as it selects only the first row I want and then all others that have .replace in them and only after that jumps to the next .replace which was preceded by .equal : 所以我想出了这个作为jQuery(“ prev + next”)选择器,但是它似乎不起作用,因为它只选择了我想要的第一行,然后选择了所有包含.replace的其他行,然后才跳转到下一个.replace之前是.equal:

$('tr:has(.equal) + tr:has(.replace),tr:has(.empty),tr:has(.delete),tr:has(.insert)')

This is slightly more efficient, but wordier: 这效率更高一些,但是更加麻烦:

$("tr:has(.equal)").next("tr:has(.empty), tr:has(.insert), tr:has(.delete), tr:has(.replace)")

Fiddle , jsPerf 小提琴jsPerf

Select the previous elements, then use .next . 选择前面的元素,然后使用.next

$(".equal").closest("tr").next().has(".replace,.empty,.delete,.insert");

It only selects table rows that have the specified classes and are preceded by a row that containing the equal class. 它仅选择具有指定类并在其前面包含equal类的行的表行。

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

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