1

我有一些表结构:

    <tr class="row-2"><tr>
    <tr class="row-3">..<tr>
    <tr class="row-4">..<tr>
    <tr class="row-5">..<tr>
    <tr class="row-6">..<tr>
    <tr class="row-7"><tr>
    <tr class="row-8">..<tr>
    <tr class="row-9">..<tr>
    <tr class="row-10">..<tr>
    <tr class="row-11">..<tr>
...etc

对于此示例,具有“row-2”和“row-7”类的 TR 是扩展子行的父产品链接。

<script>
$(function() {
    $('tr.parent')
        .css("cursor","pointer")
        .css("color","red")
        .attr("title","Click to expand/collapse")
        .click(function(){
            $(this).siblings('.child-'+this.id).toggle();
        });
    $('tr[@class^=child-]').hide().children('td');
});
</script>

行 -3...-6 是第 2 行的孩子,第 -8 ...-11 行是第 7 行的孩子

如何找到第 2 行、第 7 行等,然后添加第二类“父”和 ID 相似类(id="row-2"、id="row-7" 等)?我还需要在第 2行和第 7 行之间的每个TR类中添加等于前一个父行。归根结底,我需要这样的东西:

        <tr class="row-2 parent" id="row-2"><tr>
        <tr class="row-3 child-row2">..<tr>
        <tr class="row-4 child-row2">..<tr>
        <tr class="row-5 child-row2">..<tr>
        <tr class="row-6 child-row2">..<tr>
        <tr class="row-7 parent" id="row-7"><tr>
        <tr class="row-8 child-row7">..<tr>
        <tr class="row-9 child-row7">..<tr>
        <tr class="row-10 child-row7">..<tr>
        <tr class="row-11 child-row7">..<tr>
..etc
4

1 回答 1

0

一种方法是对所有行执行两次,以设置所需的类和 id。在第一遍中,添加一个与类名相同的 id,并将类添加parent到第 2 行和第 7 行。在第二遍中,找到每一.parent行,并将child-<id>类添加到他们的兄弟姐妹,直到下一个父母。这不是对第 2 行和第 7 行的值进行硬编码,而是假定所有标题项都包含在一个<th>元素内,而不是一个<td>元素内。

这是一些代码:http: //jsfiddle.net/vYTW2/

/**
 * Do a two pass on all rows to set them up.
 * In the first pass, add the same id as class, and
 * add the "parent" class to the row.
 *
 * Assuming all product header rows contain a
 * <th> element
 */
$('table tr th').each(function() {
    var row = $(this).parent('tr');
    var id = row.attr('class');
    row.attr('id', id);
    row.addClass('parent');
});

/**
 * In the second pass, run through all header rows
 * (that have the class parent) and mark all next siblings
 * with class "child-rowX" until we see the next parent row.
 */
$('tr.parent').each(function() {
    var id = $(this).attr('id');
    var className = 'child-' + id;
    $(this).nextUntil('.parent').addClass(className);
});
于 2010-03-29T05:05:05.687 回答