Edit jQuery Datatable fields

2020-02-13 03:01发布

问题:

I would like to output a bootstrap label for one value of a field in a JQuery dataTable. This fields possible values can be '0' or '1' and depending on the result I want to decide which bootstrap label I want to output in the dataTable. Unfortunately I don't know how I can do this if statement for this case.

My JQuery:

$(document).ready(function() {  
    $('#accountOverview').dataTable( {
        "ajax": {
            "url": "/database/accounts.php",
            "data": {"action": "selectAccounts"},
            "dataSrc": ""
        },
        "columns": [
            { "data": "email" },
            { "data": "platform" },
            { "data": "coins" },
            { "data": "profitDay" },
            { "data": "playerName" },
            { "data": "tradepileCards" },
            { "data": "tradepileValue" },
            { "data": "enabled" }
        ],
        "autoWidth": false
    });
});

I need to use something like this for the result of the "enabled" field:

if(enabled==1) <label class="label label-success">Online</label>
else <label class="label label-error">Offline</label>

HTML Table:

<table id="accountOverview" class="table datatable">
    <thead>
        <tr>
            <th>E-Mail</th>
            <th>Platform</th>
            <th>Coins</th>
            <th>Profit last 24h</th>
            <th>Playername</th>
            <th>Tradepile Cards</th>
            <th>Tradepile Value</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody id="accountList">
        <!-- List all accounts -->
    </tbody>
</table>

The label needs to be in the field "status" = the last each row.

回答1:

Following dataTable's "draw" (which happens after AJAX loads your data), you can look up the last td of each row and use wrapInner() to inject the HTML you want. So, in your case, try:

var apply_label=function(){
    $('#accountOverview').find('td:last-child').not(':has(.label)').each(function(){
        if( this.innerHTML==="1"){
            $(this).wrapInner('<span class="label label-success"></span>');
        }
        else {
            $(this).wrapInner('<span class="label label-danger"></span>');
        }
    });
};
$('#accountOverview').dataTable( {
    "ajax": {
        "url": "/database/accounts.php",
        "data": {"action": "selectAccounts"},
        "dataSrc": ""
    },
    "columns": [
        { "data": "email" },
        { "data": "platform" },
        { "data": "coins" },
        { "data": "profitDay" },
        { "data": "playerName" },
        { "data": "tradepileCards" },
        { "data": "tradepileValue" },
        { "data": "enabled" }
    ],
    "autoWidth": false,
    "drawCallback": function( settings ) {
        apply_label();
    }
});

Notes:

  1. I think you want span (not label).
  2. I think you want .label-danger (not .label-error).

Check it out at http://jsfiddle.net/jhfrench/wrkkbcf1/.