模板文字HTML表格中的三元运算符

时间:2018-09-19 18:32:23

标签: javascript css ternary-operator template-literals

如果状态为“失败”,我试图将表格数据设置为红色的背景色。我很难设置这种内联样式。最初,我尝试在createTableData函数的第二个td中使用三元运算符,但无法使其正常工作。现在,我正在尝试将其分解成自己的功能,但都不起作用。

正在寻求有关设置表格数据背景颜色的帮助。

HTML

<body>
<div class="container-fluid">
    <div class="jumbotron">
        <h1 class="text-center mb-3">
            Active Directory Replication Health
        </h1>
    </div>



<div id="table"></div>


</div>


<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
<script src="js/script.js"></script>

脚本

var data = [

{
    "DC":  "SV07CTDC1",
    "Connectivity":  "Passed",
    "Advertising":  "Failed"
},
{
    "DC":  "SVGCCTDC1",
    "Connectivity":  "Passed",
    "Advertising":  "Failed"
}
];

function checkStatus(status) {
status === "Failed" ? "background-color: red" : "background-color: blue"
}


function createTableData(dc ){
var html = ''
for( key in dc )
    html += `   
        <tr>
            <td> ${key} </td>
            <td style=${checkStatus(dc[key])} > ${dc[key]} </td>
        </tr>

`
return html
}


function createTable(dc) {
return `
    <div class="col-md-3 col-sm-6  ">
        <table class="table table-dark table-striped table-bordered table-hover">

                ${createTableData(dc)}



        </table>
    </div>  
`
}






document.getElementById("table").innerHTML = `
<div class="row">
    ${data.map(createTable).join("")}
</div>
`

1 个答案:

答案 0 :(得分:2)

checkStatus 方法中唯一缺少的是返回条件结果;

  var that = this; 

  this.questionclick = function() {chkVals(that);}

  for (i = 0; i < choices.length; i++) {
  var x = document.getElementById(choices[i]);
  x.addEventListener("blur", function() {chkVals(that);}, true);

  };

更新了codepen