将新行放在jQuery数据表的特定位置 [英] Put new rows at the specific position of the jQuery datatable

查看:53
本文介绍了将新行放在jQuery数据表的特定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DEFAULT

我创建 ajax datatable ,哪些行有时会被表格末尾的json填充:< a href =http://jsfiddle.net/jezrael/7j19hj5s/2/ =nofollow noreferrer> jsfiddle ,有时候在表格的顶部。这取决于ajax响应的时间。

DEFAULT
I create ajax datatable, which rows are sometimes filled by json in the end of table: jsfiddle and sometimes in the top of table. It depends of time of ajax response.

推荐输出

我有来自两个不同来源和输出的两个输入jsons是这张表:

RECOMMENDED OUTPUT
I have two input jsons from two different sources and output is this table:

<table>
    <tr><td>1</td><td>2</td><td>3</td></tr>
    <tr><td>1</td><td>2</td><td>3</td></tr>
    <tr><td>1</td><td>2</td><td>3</td></tr>
    ...
    <tr><td>1</td><td>2</td><td>3</td></tr>
    <tr><td>1</td><td>2</td><td>3</td></tr>
    <tr><td>8</td><td>7</td><td>6</td></tr> <!-- inserted row-->
    <tr><td>8</td><td>7</td><td>6</td></tr> <!-- inserted row-->
    <tr><td>8</td><td>7</td><td>6</td></tr> <!-- inserted row-->
    <tr><td>8</td><td>7</td><td>6</td></tr> <!-- inserted row-->
    <tr><td>1</td><td>2</td><td>3</td></tr>
    <tr><td>1</td><td>2</td><td>3</td></tr>
    ...
    <tr><td>1</td><td>2</td><td>3</td></tr>
</table>

2. json中的行插入表(从1. json创建)到特定位置。这个位置是常数,长度为1和2. json数据是恒定的。

Rows from 2. json are inserted in table (created from 1. json) to specific position. This position is constant, lengths of 1. and 2. json data are constant.

第一个解决方案

我有添加包含数字的第一列并按其降序排序数据表 - jsfiddle 。我可以隐藏第一列 jsfiddle ,但我更喜欢使用自定义功能,因为它没有在IE8中工作。

FIRST SOLUTION
I have to add first column containing a number and sort the datatable descending by it - jsfiddle. I can hide first column jsfiddle, but I rather use custom function, because it doesn't work in IE8.

var t = $("#tab1").DataTable({
    "ajax": "data1.json",
    columnDefs: [
         { className: "hide", "targets": [ 0 ] },
         ], 
    "columns": [
        { "data": "id"},
        { "data": "cat1"},
        { "data": "cat2"},
        { "data": "cat3"}
    ]
});

$.ajax({
    type: "GET",
    url: "data2.json",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        t.rows.add(response.data); 
        t.draw();
    }
  });

IDEA - CUSTOM FUNCTION

我尝试创建自定义函数 rows.addinposition(rows,position),但它可以作为函数 rows.add()。< br>
我在 jquery.dataTables.js 中的函数rows.add DataTables / blob / master / media / js / jquery.dataTables.js #L7879rel =nofollow noreferrer> 7879行,我更改了 out.push() out.splice() 拼接文档

IDEA - CUSTOM FUNCTION
I try to create custom function rows.addinposition(rows, position), but it works as function rows.add().
I copied and modified function rows.add found in jquery.dataTables.js at line 7879, I changed out.push() to out.splice() splice docs.

我知道,不推荐,更好的是扩展datatables api ...

I know, it is not recommended, better is extend datatables api...

_api_register( 'rows.addinposition()', function ( rows, position ) {
    var newRows = this.iterator( 'table', function ( settings ) {
            var row, i, ien;
            var out = [];

            for ( i=0, ien=rows.length ; i<ien ; i++ ) {
                row = rows[i];

                if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
                    //ROWS.ADD USE OUT.PUSH
                    //out.push( _fnAddTr( settings, row )[0] );
                    //CHANGED TO OUT.SPLICE
                    out.splice( position, 0, _fnAddTr( settings, row )[0] );
                }
                else {
                    out.splice( position, 0, _fnAddData( settings, row ) );
                }
            }
            console.log(out);
            return out;

        }, 1 );

    // Return an Api.rows() extended instance, so rows().nodes() etc can be used
    var modRows = this.rows( -1 );
    modRows.pop();
    modRows.push.apply( modRows, newRows.toArray() );

    return modRows;
} );    

如果你可以帮助我的话会很棒。

It would be great if you could help me.

我发现了类似的问题:

  • SO link: function fnAddData() in version 1.9 Datatables
  • SO link - add multiply rows to end of datatable
  • SO link - no answer
  • datatables forum link - old version, no answer (I think)

编辑

谢谢davidkonrad,但我在 jsfiddle ,我发现了2个问题:

EDIT
Thank you davidkonrad, but I test it in jsfiddle, and I found 2 problems:


  • 订购错误2.,1,而不是1.,2。 - 我认为容易出问题

  • 有时这些添加的行位于表格的顶部,有时位于正确的位置。随机。 - 也许是大问题

我在 jsfiddle 及其行为非常奇怪:

I debug it in jsfiddle and its behaviour is very strange:

console.log('rowCount = '+rowCount);

如果行位于顶部(不良位置)返回:

rowCount = 0
rowCount = 1

没有循环,因为firebug没有显示 var i

and for didn't loop, because firebug doesn't show var i.

如果他们处于有利位置,则返回:

rowCount = 5
rowCount = 6

for 循环和 var i 在此示例中返回:

1. loop:

and for looped and var i returned in this example:
1. loop:

i = 5 
i = 4 
i = 3

2.loop:

i = 6 
i = 5 
i = 4 
i = 3

我错过了什么吗?为什么订单很奇怪?

Did i missed something? Why order is strange?

推荐答案


解决方案

我相信你需要使用jQuery $。当 时,两个Ajax调用都成功执行回调。

I believe you need to use jQuery $.when function to execute callback when both Ajax calls were successful.

这样,您可以按相同顺序获取数据始终,并且无需编写函数来在特定位置插入数据。

That way you get data always in the same order and there is no need to write functions to insert data at specific position.

此外,如果需要,您可以在使用它初始化数据表之前操作最终数据。例如,下面显示的只有两个选项,可能性是无限的。

Also, if needed, you can manipulate the final data before initializing the data table with it. For example, shown below are just two options, the possibilities are limitless.

call2 来自的数据call1

To append data from call2 to data from call1:

var data = a1[0].data.concat(a2[0].data);

call2 插入数据位于 2 的数据来自 call1 来源):

To insert data from call2 at position 2 of data from call1 (source):

var data = a1[0].data;
data.splice.apply(data, [2, 0].concat(a2[0].data));




DEMO

请参阅下面的示例以获取代码和演示。

See example below for code and demonstration.

$(document).ready(function(){
   var call1 = $.ajax({
      url: "https://api.myjson.com/bins/48g56",
      type: "GET",
      dataType: "json",
      contentType: "application/json; charset=utf-8",
   });

   var call2 = $.ajax({
      url: "https://api.myjson.com/bins/1bfa2",
      type: "GET",
      dataType: "json",
      contentType: "application/json; charset=utf-8",
   });
   
   
   // When both Ajax requests were successful
   $.when(call1, call2).done(function(a1, a2){
      // a1 and a2 are arguments resolved for the call1 and call2 ajax requests, respectively.
      // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
     
      // Append data from call2 to data from call1
      // var data = a1[0].data.concat(a2[0].data);
     
      // Insert data from call2 at position 2 of data from call1
      var data = a1[0].data;
      data.splice.apply(data, [2, 0].concat(a2[0].data));
     
      // Initialize data table
      var t = $("#tab1").DataTable({
         data: data,
         columnDefs: [
            { className: "hide", "targets": [ 0 ] },
         ], 
         order: [],
         ordering: false,        
         columns: [
            { "data": "id"},
            { "data": "cat1"},
            { "data": "cat2"},
            { "data": "cat3"}
         ]
      });
   });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdn.datatables.net/1.10.7/js/jquery.dataTables.js"></script>
<link href="http://cdn.datatables.net/1.10.7/css/jquery.dataTables.css" rel="stylesheet"/>


<table id="tab1" class='data tab01'>
	<thead>
		<tr>
 			<th>id</th>
            <th>cat1</th>
			<th>cat2</th>
			<th>cat3</th>
		</tr>
	</thead>
	<tbody>
	</tbody>
</table>

这篇关于将新行放在jQuery数据表的特定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆