2012-07-05 97 views
0

已将早上花在示例页面上,似乎无法找到为什么这不起作用。如何在数据表中插入TD

意图是用ajax(当前是一个示例txt文件)填充表,并向每行添加一列以允许编辑和删除。已经尝试了下面的代码的各种变体(已经演变为丑陋),但可以明白为什么它不起作用。没有任何错误(在萤火虫或任何其他地方),它只是不会添加列作为“应该”执行的代码。

jQuery(document).ready(function($) { 
    $(function() { 
     tableActions(); 

     function initTable() 
     { 
      var myTable = $('#example').dataTable({ 
       "iDisplayLength": 10, 
       "bJQueryUI": true, 
       "sPaginationType": "full_numbers", 
       "bProcessing": true, 
       "bStateSave": false, 
       "sAjaxSource": 'datatables_example_arrays.txt', 
       "aLengthMenu": [[10, 15, 25, -1], [10, 15, 25, "All"]], 
       "bRetrieve": true 
      }); 
      return myTable; 
     } 

     function tableActions() 
     { 
      var oTable = initTable(); 
      /* Insert an 'edit' column with image to the table */ 
      var nCloneTh = document.createElement('th'); 
      var nCloneTd = document.createElement('td'); 
      nCloneTd.innerHTML = '<img src="title_edit.png">'; 
      nCloneTd.className = "center"; 

      $('#example thead tr').each(function() { 
       oTable.insertBefore(nCloneTh, this.childNodes[0]); 
      }); 

      $('#example tbody tr').each(function() { 
       oTable.insertBefore( nCloneTd.cloneNode(true), this.childNodes[0]); 
      }); 
     } 
    }); 
}); 

回答

1

根据http://api.jquery.com/insertBefore/

你想这样的:

$('#example thead tr').each(function() { 
    $(nCloneTh).insertBefore(this.childNodes[0]); 
}); 

但也许更多的 “jQuery的” 办法做到这一点是:

$('#example thead tr').prepend(nCloneTh); //untested but should work 

编辑

好吧,我在他的例子和你的例子中看到的唯一真正的区别是他在初始化dataTables之前附加了“行扩展器”td。

我不知道你的JSON输入是什么样子,但是这是我做我的(我会尽量使之显得有些通用):

aoColumns: [{ 
    mDataProp: 'Id', 
    sClass: 'center', 
    bUseRendered: false, 
    fnRender: function (o) { 
     return '<img src="media/open.png" class="row-expander" alt="" />'; 
    } 
}, { 
    mDataProp: 'NoteCount', 
    sClass: 'center',   
    bUseRendered: false, 
    fnRender: function (o) { 
     return String.format('<img src="media/blue/{0}.png" alt="" class="notes-count" />', o.aData.NoteCount); 
    } 
}, { 
    mDataProp: 'Name', 
    bUseRendered: false, 
    fnRender: function (o) { 
     return String.format('<a href="./MyObjHome.aspx?ID={1}">{0}</a>', o.aData.Name, o.aData.Id); 
    } 
}, // add more columns 
] 

这样你就不需要每当表格重新渲染时都会添加额外的单元格... dataTables的内部将处理您的'假'列,该列只存在用于展开状态的图像。

如果您使用的是二维数组而非对象数组,那么这会有点棘手。在上面的例子中我的数据源看起来类似:

[{ 
    Id: some-guid, 
    Name: 'My Object Name', 
    NoteCount: 4 
}, { 
    Id: some-guid-2, 
    Name: 'My Second Name', 
    NoteCount: 10 
}] 
+0

根据他们的榜样,是不是需要为每个克隆:http://datatables.net/release-datatables/examples/api/row_details.html – GDP 2012-07-05 19:22:50

+0

@GDP:你说得对,我错过了那里的'cloneNode'电话,很抱歉。 – BLSully 2012-07-05 19:42:09