HTMLで文字の色を変更するにはクラスを付与するか、style属性にCSSを直接書き足して実装します。
- クラス付与:
<span class="list_type red">
←このように半角スペースで区切る事で複数クラスを宣言可能
- style属性:
<span class="list_type" style="color: red;">
testList[i].typeがAというタイプだった時のみ文字色を変えたい
上記を踏まえてJSのコードに落とし込んだ場合、if文か三項演算子で実現させます。
今回はif文で記載してみます。
JavaScript
1function showTestList(testList) {
2 var html = ''
3 if (testList != null) {
4 for (var i = 0; i < testList.length; i++) {
5 if (testList[i].type === 'A') {
6 html += '<span class="list_type red">' + 'type: ' + testList[i].type + '</span>';
7 } else {
8 html += '<span class="list_type">' + 'type: ' + testList[i].type + '</span>';
9 }
10 }
11 }
12}
【おまけ】更にかっこいい書き方
既存のコードでは同じような行が2つ存在しています。
これを一つにまとめてみます。
色々方法はありますが、クラスが1個か2個かなのでその編を考慮してみました。
(上記採用されなかった三項演算子も使ってみます)
JavaScript
1function showTestList(testList) {
2 var html = ''
3 if (testList != null) {
4 for (var i = 0; i < testList.length; i++) {
5 var classes = testList[i].type === 'A' ? ['list_type', 'red'] : ['list_type'];
6 html += '<span class="' + classes.join(' ') + '">' + 'type: ' + testList[i].type + '</span>';
7 }
8 }
9}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/19 02:42