2012-02-09 26 views
1

我有以下表結構:添加新的HTML行到一組HTML表格內

<table id="myTable"> 
    <tr id="myRow" class="content"> 
     <td>Option 1</td> 
    </tr> 
     <tr class="content"> 
     <td>Option 2</td> 
    </tr> 

    <tr class="altcontent"> 
     <td>file code 1 </td> 
    </tr> 
     <tr class="altcontent"> 
     <td>file code 2</td> 
    </tr> 

     <tr class="content"> 
     <td>Option 3</td> 
    </tr> 
     <tr class="content"> 
     <td>Option 4</td> 
    </tr> 

     <tr class="altcontent"> 
     <td>file code 3 </td> 
    </tr> 
     <tr class="altcontent"> 
     <td>file code 4</td> 
    </tr> 

</table> 

var newContentRow = $("<tr></tr>"); 

我想選項2和選項4.當然之後添加newContentRow,這只是一個例如,許多或非文件代碼行都有很多選項。

任何想法!

更新1:

我更新了我的代碼以下的建議如下:

var searchClass = "TBLCONTENTS"; 

    var rows = $("#" + rowId).parent().children("tr"); 

    for(i=0;i<rows.length;i++) { 


     if ($(rows[i]).attr('class') != searchClass && $(rows[i]).prev().attr('class') == searchClass) { 

      $(rowToBeAdded).addClass("TBLCONTENTS"); 
      $(rows[i]).before(rowToBeAdded); 

    }    
    } 

甚至去檢查,如果裏面並執行。之前的功能,但我只看到一排添加到第二組,而不是第一組。

回答

1
// Loop through each row, 
// ... if the current class is different than your desired set, 
// ... and the previous row is the same as your desired set, 
// ... inject a row before it. 

classSet='content'; 

$('#myTable TR').each(function(){ 

    if($(this).attr('class') != classSet && $(this).prev().attr('class') == classSet){ 

     $(this).before('<tr class="' + classSet + '"><td>new option</td></tr>'); 

    } 

}); 
+0

優秀的解決方案。比我想象的要好! – 2012-02-09 17:59:57

+0

我實際上改變了這一點,因爲我得到的印象是他只想添加一個新的行來設置具有特定類別(即「內容」而不是「altcontent」)。 – 2012-02-09 18:07:58

+0

請參閱我更新的帖子,我已經使用了您的方法! – azamsharp 2012-02-09 20:36:10

0

試試這個。

$('#myTable') 
.find('td:contains("Option 2")' 
.parent() 
.after("<tr><td></td></tr>") 

不像我以前:contains()找到一行之後/你需要添加一個新的行之前,你可以使用任何選擇。使用after方法在行之後添加新行或before將其添加到行之前。

+0

選項2只是一個例子!它可以是任何東西。我認爲我需要對類名做些什麼,因爲它們是不同的。 – azamsharp 2012-02-09 17:11:22

+0

是的,您可以使用任何選擇器來查找之前或之後必須添加該行的行。 – ShankarSangoli 2012-02-09 17:12:14

+0

在您的代碼中,它會在每個選項後添加新行。我不要那個。我需要在每組選項中添加一行。 – azamsharp 2012-02-09 17:13:29