【问题标题】:Using jQuery, how do I find all instances of a class that appear between another class使用 jQuery,如何找到出现在另一个类之间的类的所有实例
【发布时间】:2023-10-19 01:35:01
【问题描述】:

例如:

<table>
  <tr class="highlight" id="click">
    <td>Rusty</td>
  </tr>
  <tr class="indent">
    <td>Dean</td>
  </tr>
  <tr class="indent">
    <td>Hank</td>
  </tr>
  <tr class="highlight">
    <td>Myra</td>
  </tr>
</table>

假设当我点击 hr 的 id 为 click 时,我将如何找到 indent 类的所有实例,直到 highlight 类的下一个实例?

【问题讨论】:

    标签: javascript jquery jquery-selectors traversal


    【解决方案1】:
    $('tr.highlight').click(function() {
        var $indents = $(this).nextAll('tr.indent');
    });
    

    编辑

    这似乎选择了所有 .indents 而不管 .highlights。试试这个:

    $('tr.highlight').click(function() {
        var row = $(this).next();
        var selection = false;
        while(row.hasClass('indent')) {
            if(!selection) {
                selection = row;
            } else {
                selection.add(row);
            }
            row = row.next();
        }
    });
    

    【讨论】:

    • 唯一的问题是在下一个高亮之后是否有更多缩进。
    【解决方案2】:

    这仅将单击应用于具有“单击”的突出显示,并仅返回“单击”和它遇到的下一个突出显示之间的缩进。

    它使用 jQuery ~“下一个兄弟姐妹”选择器为您完成更多工作。

    http://jsfiddle.net/w_barath/bFZnH/2/

    $("#click").bind('click', function() {
        var good = true;
        $("#click ~ tr").each(function(e) {
            if (this.className == "highlight") {
                good = false;
            }
            if (good && this.className == "indent") {
                this.style.background="red";
            }
        });
    });
    

    【讨论】: