0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

setCellでstyleベタ打ちではなくclassを設定する

Posted at

やりたいこと

gridComplete()で条件に当てはまるセルに色を付ける。
その際、「{ background: color }」の部分をcssに定義したクラス名としたい。

sample.js
function gridComplete() {
      var grid = $('#list');
      var rows = grid.getRowData(); //get data
      for (var idx in rows) {
        var row = rows[idx];
        var color;
        // define colors
        if (row.statusCode == '1') {
          color = '#99FF99'; // Light green 
        } else {
          color = '#FF6666'; //Light red
        }
        grid.setCell(row.id, 'program', '', { background: color }); 
        grid.setCell(row.id, 'status', '', { background: color }); 
      }
    };

そもそもsetCellってなんぞや

使い方はこんな感じ↓
(グリッドテーブル).setCell(行を特定するなにか, 列名, 変更後の値(空の場合変更しない), スタイル);

つまり↓は、

grid.setCell(row.id, 'status', '', { background: color }); 

grid : グリッドテーブル
row.id : 行を特定するid
status : 列名は"status"
{ background: color } : ←スタイル
…ってことになりますね。

ほんならcssに定義しよか

csjsにスタイルベタ書きは管理の面でよくないのでcssで一括管理しましょう(基本)。

style.css
.test-green{
    background: #99FF99
}
.test-red{
    background: #FF6666
}

これをsetCellするにはこう。

sample2.js
function gridComplete() {
      var grid = $('#list');
      var rows = grid.getRowData(); //get data
      for (var idx in rows) {
        var row = rows[idx];
        var color;
        // define colors
        if (row.statusCode == '1') {
          color = 'test-green'; // #99FF99
        } else {
          color = 'test-red'; // #FF6666
        }
        grid.setCell(row.id, 'program', '',color); 
        grid.setCell(row.id, 'status', '', color); 
      }
    };

setCellの第四引数にclass名を渡してあげればOK。
これにより、cssで色管理ができる。

【ちょっと解説】
「color = 'test-green';」ないし「color = 'test-red';」でcolorにクラス名を定義。
それを第四引数に渡している。

ハマったこと

「color = '.test-red'; 」のように、「.」をつけちゃうとcssが反映されないので注意。
あくまで渡すのはcss定義済みのクラス名だけでよい。

参考にした記事

setCell method > how to set class of the fourth parameter?
imuiListTableで行の背景色を動的に変更する方法

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?