2010-03-29 35 views
1

之間乘次班,我有一些表結構:如何查找和n更改&N

<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 

與類這個例子TR「行2」和「行7」是parrent產品鏈接至極展開子行。

<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 =「第2行」,ID =「第7行」等)?我還需要在每個TR之間第2行第-7行類等於以前的父行。在底線我需要這樣的事情:

 <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 

回答

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

感謝。但我今天看看我的表格代碼。父行中沒有TH。只有TR類=「行X」 這裏產生的所有行是我需要http://jsfiddle.net/KUyb8/ 這裏是我有http://jsfiddle.net/YVqdS/(生成表格) – 2010-03-30 06:11:50

+0

看起來微唯一的事情是'-'在TD列,這看起來太脆弱了。如果你已經知道標題行,你可以單獨運行它們的第一遍。用於離。)'$(」。行-2,.row-9' )。每個(()的函數的{',而不是尋找'' – Anurag 2010-03-31 07:36:52