2014-02-23 54 views
0

我無法刪除所有單元格的列。它工作正常,如果我試圖刪除最後一列,但如果我試圖刪除最後一列,它不會按預期工作。無法刪除單元格的列

這是我的HTML看起來像:

 <table id="tblData"> 
      <thead> 
       <tr style="background-color:green" id="trMain"> 
        <th>Fixed 1</th> 
        <th>Fixed 2</th> 
        <th>Fixed 3</th> 
        <th id="Collection1">Collection 1</th> 
        <th id="Collection2">Collection 2</th> 
       </tr> 
       <tr style="background-color:red" id="trSub"> 
        <th>E1</th> 
        <th>E2</th> 
        <th>E3</th> 
        <th> 
         <table> 
          <thead> 
           <tr> 
            <th>P1</th> 
            <th>P2</th> 
            <th>P3</th> 
           </tr> 
          </thead> 
         </table> 
        </th> 
        <th> 
         <table> 
          <thead> 
           <tr> 
            <th>P1</th> 
            <th>P2</th> 
            <th>P3</th> 
           </tr> 
          </thead> 
         </table> 
        </th> 
       </tr> 
      </thead> 
     </table> 


<button type="button" id="btnGet">Delete a Column</button> 

這是我的JS怎麼樣子:

$(document).ready(function() { 
    var colToDelete = 'Collection2'; 
    $('#btnGet').click(function(){ 

      var column = $("#tblData").find('#' + colToDelete); 
      var row = column.parent('tr').children(); 
      var idx = row.index(column); 
      alert(idx) 
      $("#trMain").find("th:eq(" + idx + ")").remove(); 
      alert(idx) 
      $("#trSub").find("th:eq(" + idx + ")").remove(); 

    }); 
}); 

這裏是JS小提琴:http://jsfiddle.net/cH654/

回答

0

我已經更新了你的腳本,這應該工作

$(document).ready(function() { 
var colToDelete = 'del1'; 
$('#btnGet').click(function(){ 

     var column = $("#tblData").find('#' + colToDelete); 
     var row = column.parent('tr').children(); 
     var idx = row.index(column); 
     $("#trMain").find("th:eq(" + idx + ")").remove(); 
     $("#trSub > th:eq(" + idx + ")").remove(); 

}); 
}); 
0

您遇到問題是因爲您在表格中放置了一個表格,所以兩行的列不對應。你的第二行應該是這樣的:

<tr style="background-color:red" id="trSub"> 
     <th>E1</th> 
     <th>E2</th> 
     <th>E3</th> 
     <th>P1 P2 P3</th> 
     <th>P1 P2 P3</th> 
</tr> 

而且你的jQuery函數應該是如此簡單:

$('#btnGet').click(function(){ 
    $("#trMain th").last().remove(); 
    $("#trSub th").last().remove();  
}); 

這裏工作:http://jsfiddle.net/cH654/5/

+0

我把P1,P2,P3在單獨的原因表是因爲我希望他們作爲列。他們是一個集合中的3個不同的列。像Matrix一樣。 – Asdfg