添加类以附加数据

时间:2016-06-08 02:41:59

标签: jquery twitter-bootstrap

我正在使用jQuery并且有一些来自websocket的数据。数据状态被确认,打开和关闭。

我将数据附加到表

$(".incident-row").append(
        "<tr><td>"+incident.data.id+"</td>"
        +"<td>"+incident.data.state+"</td>"
        +"<td>"+incident.data.brief+"</td>"
        +'<td><button type="button" class="btn btn-primary btn-sm">View details</button></td>'
        +"</tr>"
        );

我现在想使用bootstrap将绿色,灰色或红色背景类添加到状态,具体取决于状态本身。该类正确附加,但使用DOM

中的新类覆盖现有类

如何重写这个,以便每个类都停留在if语句的受影响行上?

if(incident.data.state === "OPEN"){
            $('.incident-row tr').addClass("table-danger");
         }
         else if(incident.data.state === "ACKNOWLEDGED"){
            $('.incident-row tr').addClass("table-active");
         }
         else if(incident.data.state === "CLOSED"){
            $('.incident-row tr').addClass("table-success");
         }
         else{
            return;
         }

3 个答案:

答案 0 :(得分:2)

$(&#39; .incident-row tr&#39;)的选择器正在选择所有事件行。

您可以使用包含选择器。

$('.incident-row tr:contains("OPEN")').addClass("table-danger");
$('.incident-row tr:contains("ACKNOWLEDGED")').addClass("table-active");
$('.incident-row tr:contains("CLOSED")').addClass("table-success");

答案 1 :(得分:0)

var className = "";
if (incident.data.state === "OPEN") {
    className = "table-danger";
} else if (incident.data.state === "ACKNOWLEDGED") {
    className = "table-active";
} else if (incident.data.state === "CLOSED") {
   className = "table-success";
} else {

}

$(".incident-row").append(
        "<tr class=\"" + className + "\"><td>"+incident.data.id+"</td>"
        +"<td>"+incident.data.state+"</td>"
        +"<td>"+incident.data.brief+"</td>"
        +'<td><button type="button" class="btn btn-primary btn-sm">View details</button></td>'
        +"</tr>"
        );

答案 2 :(得分:0)

尝试这个简单的解决方案:

var stateClass = {"OPEN":"table-danger","ACKNOWLEDGED":"table-active","CLOSED":"table-success"};

$(".incident-row").append(
        "<tr class=\"" + stateClass[incident.data.state]+ "\"><td>"+incident.data.id+"</td>"
        +"<td>"+incident.data.state+"</td>"
        +"<td>"+incident.data.brief+"</td>"
        +'<td><button type="button" class="btn btn-primary btn-sm">View details</button></td>'
        +"</tr>"
        );