开发者

Using jQuery, how do I find all instances of a class that appear between another class

For example:

<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>

Say when I click on the hr with the id click how would I find all instances of class indent until the next i开发者_如何学Gonstance of class highlight?


$('tr.highlight').click(function() {
    var $indents = $(this).nextAll('tr.indent');
});

EDIT

That's seems to select all .indents regardless of .highlights. Try this:

$('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();
    }
});


This applies the click only to the highlight with "click" and returns only the indents between "click" and the next highlight it encounters.

It uses the jQuery ~ "next siblings" selector to do a little more of the work for you.

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";
        }
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜