admin管理员组

文章数量:1336421

I have an existing jQuery dataTables object in my html page.

I need to update a few <a href> elements in all <td>s on the first <tr> of the datatables by clicking on a refresh button which triggers an Ajax call to retrieve the new data in JSON.

The <a href> elements are dynamically constructed with the hyper links retrieved by Ajax, so I need to have the html for each <a href> element.

<tr id="LoJXi76DH3" role="row" class="odd">
    <td><a data-transition="pop" data-mini="true" data-position-to="window" data-rel="popup" href="#deleteThisRunModel" onclick="copyRunModelObjId(&quot;LoJXi76DH3&quot;);" title="Delete this job"><img width="16" height="16" src="css/img/Remove24.png"></a></td>
    <td><span>LoJXi76DH3</span></td>
    <td><span>500</span></td>
    <td><span>Completed</span></td>
    <td><span>Firstname Lastname</span></td>
    <td><span>9/12/2015, 1:07:39 PM</span></td>
    <td><span>9/12/2015, 1:18:47 PM</span></td>
    <td><span>Successful</span><span> </span><a title="Details" class="my-tooltip-btn ui-btn ui-alt-icon ui-nodisc-icon ui-btn-inline ui-icon-info ui-btn-icon-notext" data-transition="pop" data-rel="popup" href="#popupRMDetails_LoJXi76DH3">Details</a></td>
    <td><a target="_blank" href="View.jsp?res=500&amp;url=myImage.png">View</a><span> </span><a href="myServlet?action=exportForDownload&amp;jobOID=LoJXi76DH3">Download</a></td>
</tr>

Just wondering which function/api should I use to get this done?

I have an existing jQuery dataTables object in my html page.

I need to update a few <a href> elements in all <td>s on the first <tr> of the datatables by clicking on a refresh button which triggers an Ajax call to retrieve the new data in JSON.

The <a href> elements are dynamically constructed with the hyper links retrieved by Ajax, so I need to have the html for each <a href> element.

<tr id="LoJXi76DH3" role="row" class="odd">
    <td><a data-transition="pop" data-mini="true" data-position-to="window" data-rel="popup" href="#deleteThisRunModel" onclick="copyRunModelObjId(&quot;LoJXi76DH3&quot;);" title="Delete this job"><img width="16" height="16" src="css/img/Remove24.png"></a></td>
    <td><span>LoJXi76DH3</span></td>
    <td><span>500</span></td>
    <td><span>Completed</span></td>
    <td><span>Firstname Lastname</span></td>
    <td><span>9/12/2015, 1:07:39 PM</span></td>
    <td><span>9/12/2015, 1:18:47 PM</span></td>
    <td><span>Successful</span><span> </span><a title="Details" class="my-tooltip-btn ui-btn ui-alt-icon ui-nodisc-icon ui-btn-inline ui-icon-info ui-btn-icon-notext" data-transition="pop" data-rel="popup" href="#popupRMDetails_LoJXi76DH3">Details</a></td>
    <td><a target="_blank" href="View.jsp?res=500&amp;url=myImage.png">View</a><span> </span><a href="myServlet?action=exportForDownload&amp;jobOID=LoJXi76DH3">Download</a></td>
</tr>

Just wondering which function/api should I use to get this done?

Share Improve this question edited Dec 14, 2015 at 6:04 davidkonrad 85.6k17 gold badges209 silver badges271 bronze badges asked Dec 14, 2015 at 3:41 alextcalextc 3,52516 gold badges71 silver badges119 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

If you want to replace an entire <tr>..</tr> with a brand new or modified <tr>, you can do the following.

First locate the row you want to replace in jQuery, either with some id selector or through DOM traversal from an event like this:

var $row = $(this).closest("tr")

Let's say you have an brand new HTML row that you'd like to replace it with. This could e from an AJAX call, somewhere on the page, or a modified version of the existing row, or just straight HTML:

var newRow = $("<tr>  <td>1</td> <td>Bob</td> <td><i>23</i></td>  <tr>

If this was a plain HTML table, you could just do .replaceWith() like this:

$row.replaceWith($(newRow))

Buutttt, then DataTables doesn't know about it, so the next time you call $dt.draw(), it'll change back. Instead, you have to pass the new info into the DataTable by locating the row in DataTables and then handing it the new info.

row().data() - data represents an array of string values that are the innerHTML of each td

So we need to convert the above row to something like this:

["1","Bob","<i>23</i>"]

Here's a function that converts a row to a data table array:

function TrToData(row) {
   return $(row).find('td').map(function(i,el) {
        return el.innerHTML;
   }).get();
}

So the whole thing will look something like this:

$('.replace').click(function () {
    var $row = $(this).closest("tr")
    var newRow = $("#newRow").find("tr")[0].outerHTML

    var newRowDataArray = TrToData(newRow)  
    $dt.row($row).data(newRowDataArray).draw();
});

Demo in jsFiddle

Demon in Stack Snippets

$(function() {
	  // initialize table
    var $dt = $('#example').DataTable({
        paging:   false,
        bFilter: false, 
        bInfo: false
    });
    
 		// add row
    $('#addRow').click(function () {
        //$dt.row.add( [1,2,3] ).draw();
        var newRow = $("#newRow").find("tr")[0].outerHTML
        $dt.row.add($(newRow)).draw();
    });
    
    // replace row
    $('.replace').click(function () {
    		var $row = $(this).closest("tr")
        var newRow = $("#newRow").find("tr")[0].outerHTML
  			
        var newRowDataArray = TrToData(newRow)  
  
        //$row.replaceWith($(newRow))
        //data represents an array of string values that are the innerHTML of each td
        $dt.row($row).data(newRowDataArray).draw();
        
    });
    
    function TrToData(row) {
     	 return $(row).find('td').map(function(i,el) {
        	return el.innerHTML;
       }).get();
    }
 
});
<link href="https://cdnjs.cloudflare./ajax/libs/datatables/1.10.12/css/jquery.dataTables.css" rel="stylesheet"/>
<script src="https://ajax.googleapis./ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/datatables/1.10.12/js/jquery.dataTables.js"></script>


<table id="example" class="display" cellspacing="0" >
  <thead>
    <tr>
      <th>Hidden</th>
      <th>Name</th>
      <th>Age</th>
      <th>Replace</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Line 1 <input type="hidden" value="1"/> </td>
      <td>Bob    <input type="hidden" value="Bob"/> </td>
      <td><input type="text" value="18"/> </td>
      <td><input type="button" value="Replace" class="replace"/> </td>
    </tr>
  </tbody>
</table>

<br/>
<button id="addRow">Add New Row</button>

<table id="newRow" style="display:none">
  <tbody>
    <tr >
      <td>Line 2 <input type="hidden" value="2"/>   </td>
      <td>Ann    <input type="hidden" value="Ann"/> </td>
      <td><input type="text" value="21"/> </td>
      <td><input type="button" value="Replace" class="replace"/> </td>
    </tr>
  </tbody>
</table>

you can use jQuery for updating a specified row. for this you need to define unique id for each row. then by the following id, you can get the object of the table element and update it by ajax call. let me explain by code. here also shown how to manipulate dynamic links.

function updateJobStatus() {
        $("#data-table tr.running").each(function() {
            var obj = $(this);
            var id = $(this).find('td:eq(0)').text();
            //var id1 = $(this).attr('id');
            $.ajax({
                type: 'GET',
                dataType: 'json',
                url: 'ajaxGetPrintJob.html',
                data: 'id=' + id,
                success: function(responseData,textStatus) {
                    if (textStatus == 'success' && responseData.length > 0) {
                        var id = responseData[0].id;
                        var tagId = responseData[0].voterListTagId;
                        var createdBy = responseData[0].createdByName;
                        var locationType = responseData[0].locationType;
                        var totalJobCount = responseData[0].totalJobCount;
                        var successCount = responseData[0].successCount;
                        var failedCount = responseData[0].failedCount;
                        var status = responseData[0].status;
                        $(obj).find('td:eq(0)').html(id);
                        $(obj).find('td:eq(1)').html('<input name="app_id" id="row'+id+ '" type="checkbox" value="'+id+'" class="case"/>');
                        $(obj).find('td:eq(2)').html('<a href="showPrintJob.html?jobId='+id+'&tagId='+tagId+'&locationType='+locationType+'&w=1024&h=700&load=true&jobName='+responseData[0].name+'" class="popup">'+responseData[0].name+'</a>');
                        $(obj).find('td:eq(3)').html(createdBy);
                        $(obj).find('td:eq(4)').html(totalJobCount);
                        $(obj).find('td:eq(5)').html(successCount);
                        $(obj).find('td:eq(6)').html(failedCount);
                        $(obj).find('td:eq(7)').html(status);

                    }
                }, error: function(responseData) {
                    unblockView();
                }
            });

        });
        setTimeout(updateJobStatus, 20000);
    }

here updateJobStatus() function will fire every 20 sec by ajax calling getting data and also manipulate. here data-table refers the table id.

<table summary="search result" id="data-table" class="search-result" cellspacing="0" style="">

and the table row should be like,

<tr class="<c:if test="${loop.count % 2 !=0}"> odd-row </c:if> <c:if test="${result.status eq 'INITIALIZING'}"> running </c:if>" > 

本文标签: javascriptHow to update an existing row with HTML on an existing JQuery DatatablesStack Overflow