根据 table 中的另一列更改按钮颜色

Change button color depending on another column in table

我正在使用 Datatables with X-editable 并在 table 中有一些 bootstrap 按钮。基本上,如果用户将 editable 'Status' 列更新为 'Resolved' 我希望 'Validated' 列中的按钮变为绿色。如果状态切换回任何其他状态,它应该变回红色。

这是我的代码,如有任何帮助,我们将不胜感激。我不确定我是否应该在 x-editable 保存事件或数据tables 单击事件上执行此操作。

我有一个 fiddle 设置:http://jsfiddle.net/n74zo0ms/2/

HTML:

<div class="table-responsive">
  <table class="table table-striped table-bordered table-hover" id="dataTables">
    <thead>
      <tr>
        <th>Occured <i class="fa fa-sort"></i></th>
        <th>Status <i class="fa fa-sort"></i></th>
        <th>Validated <i class="fa fa-sort"></i></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td align="center">12/08/2015 22:36</td>
        <td><span id="status" class="status" data-type="select"></span></td>
        <td><a href="#" class="btn-sm btn-danger" style="margin-left: 5px;"><i class="fa fa-exclamation-triangle"></i> Not Validated</a></td>
      </tr>
    </tbody>
  </table>
</div>

JQuery:

//Switch button to green if status = resolved
$('#dataTables').on('click', '.btn-danger', function(e) {
  if ($('#status').text() == 'Resolved') {
    var cell = $(this).closest('td');

    $.get($(this).attr('href'), function() {
      // Update "Resolved" column
      $('#dataTables').DataTable().cell(cell).data(
        '<a href="#" class="btn-sm btn-success" style="margin-left: 5px"><i class="fa fa-thumbs-o-up"></i> Resolved</a>'
      );
    });

    e.preventDefault();
  }
});

我对您的代码进行了一些更新,以实现基于状态的按钮更改。我从 html 中删除了按钮,并向包含按钮的 td 添加了一个 class 的 .validate 。我删除了 $('#dataTables').on('click') 方法。我向 $('#status').editable({}).

添加了额外的代码

HTML改变

<tbody>
  <tr>
    <td align="center">12/08/2015 22:36</td>
    <td><span id="status" class="status" data-type="select"></span></td>
    <td class="validated"></td>
  </tr>
</tbody>

JavaScript改变

//initialize the editable column
$('#status').editable({
  url: '/post',
  pk: 1,
  source: [{
    value: 'New',
    text: 'New'
  }, {
    value: 'In Progress',
    text: 'In Progress'
  }, {
    value: 'Resolved',
    text: 'Resolved'
  }],
  title: 'Example Select',
  validate: function(value) {
    var cell = $(this).parent().parent().find(".validated");
    cell.empty();
    if(value == 'Resolved') {
      cell.append('<a href="#" class="btn-sm btn-success" style="margin-left: 5px"><i class="fa fa-thumbs-o-up"></i> Resolved</a>');
    } else {
      cell.append('<a href="#" class="btn-sm btn-danger" style="margin-left: 5px;"><i class="fa fa-exclamation-triangle"></i> Not Validated</a>');
    };
  }
});

您可以在此处查看工作示例: http://jsfiddle.net/n74zo0ms/7/